Skip to content

All topics  /  Node.js

Node Js Create Text File If Not Exists Example

Node.js ·

Hi friends,

Now, let's see the article of node js create a text file if not exist. you'll learn node.js to create a text file if it doesn't exist. In this article, we will implement a nodejs create the file if none exists. Here you will learn node js to create a file if not exist. Let's see below an example of how to create a text file if not exists node.js.

In this tutorial, we learn to create a text file if not exist in Node.js using Node FS (File System) built-in module. Node.js example programs that use fs.writeFile() function are provided. So, let's follow a few step to create an example of node js create a text file if not exists.

So, let's start follwing 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

// include node fs module
var fs = require('fs');

 
// writeFile function with filename, content and callback function
fs.writeFile('newfile.txt', 'New text file content line!', function (err) {

  
    console.log('A new text file was created successfully.');

    
});

Output:

It will create readme.txt file with following text.

New text file content line!