How to Create a File in Node.js using Node FS module

We shall learn to create a File in Node.js using Node FS (File System) built-in module. Node.js example programs that use writeFile(), appendFile() or open() function are provided.

Create a File in Node.js

Following is a step by step guide to create a new File in Node.js :

  • Step 1 : Include File System built-in module to your Node.js program
     var fs = require(‘fs‘);
  • Step 2 : Create file using one the following methods
    • writeFile() function
       fs.writeFile(‘<fileName>’,<contenet>, callbackFunction)

      A new file is created with the specified name. After writing to the file is completed (could be with or without error), callback function is called with error if there is an error reading file. If a file already exists with the name, the file gets overwritten with a new file. Care has to be taken while using this function, as it overwrites existing file if any.
      writeFile() – Example Program.

    • appendFile() function
       fs.appendFile(‘<fileName>’,<contenet>, callbackFunction)

      If the file specified in the appendFile() function does not exist, a new file is created with the content passed to the function.
      appendFile() – Example Program.

    • open() function
       fs.open(‘<fileName>’,<file_open_mode>, callbackFunction)

      If the specified file is not found, a new file is created with the specified name and mode and sent to the callback function.
      open() – Example Program.

Examples

writeFile() – Create following Node.js program to create a file in Node.js

Run the program using node command in terminal or command prompt :

The file should be created next to your example node.js program with the content ‘Learn Node FS module’.

appendFile() – Create following Node.js program to create a file in Node.js

Run the program using node command in terminal or command prompt :
The file should be created next to your example node.js program with the content ‘Learn Node FS module’.

 

open() – Create following Node.js program to create a file in Node.js

Run the program using node command in terminal or command prompt :
The file should be opened in write mode.

 

Conclusion :

In this Node.js Tutorial – Node FS, we have learnt to create a File in Node.js using Node FS (File System) module.