How to Create Text File in Node.js?

25-Aug-2022

.

Admin

How to Create Text File in Node.js?

Hi friends,

This article goes into detail on how to create a text file in node.js. you will learn how to create a text file in nodejs. I’m going to show you about create a text file in node.js. if you have a question about create a text file in nodejs then I will give a simple example with a solution. So, let's follow a few step to create an example of node js create text file example.

In this tutorial, we shall learn to create text File in Node.js using Node FS (File System) built-in module. Node.js example programs that use writeFile() function are provided. I will give a simple example of create a text file in nodejs.

Let's see below simple example with output:

Step 1: Create Node.js Project


This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app

cd my-app

npm init

Step 2: Update server.js File

server.js

const fs = require('fs');

const data = "This is the new content of the file from NiceSnippets.com.";

fs.writeFile('readme.txt', data, (err) => {

if(err) {

throw err;

}

console.log("New Text File Successfully.");

})

Output:

readme.txt

This is the new content of the file from NiceSnippets.com.

#Node JS