Node.js has predefined module for files through which you can do all the file operations like read file, open file, write file. We will discuss the step by step process to read the file and the file management system in node.js.

  • Node File System is implemented using fs module.
  • var fs=require(“fs”)
  • For calling any method we use asynchronous call as it does not block anything as compared to synchronous methods in nodejs.
  • Asynchronous method takes two parameters
  • First parameter is error
  • Second parameter is completion function callback

Below is the example code showing how you can read file in node.js using the fs module

Node.js Read File

  1. var fs = require(“fs”);
  2. fs.readFile(‘test.txt’, function (err, data)
  3. {
  4. if (err)
  5. {
  6. return console.error(err);
  7. }

console.log(“Result: ” + data.toString()); });

NODE.JS Open File:

  1. var fs = require(“fs”);
  2. fs.open(‘input.txt’, ‘r+’, function(err, fd)
  3. { if (err)
  4. {
  5. return console.error(err);
  6.  }
  7. console.log(“File opened successfully!”); });