# Node.js FS Module

In 
Published 2022-12-03

This tutorial explains to you the Node fs module (Node.js File System) and you will see an example as well.

The main Node.js usage is to create servers. A server receives a request and after that will send back a response.

In many situation, Node.js has to read, create, move files or work with directories on the server side. This is done using fs (File System) module in Node.js.

In order to use the fs module in Node.js, you have to import that built-in module:

var fs = require("fs");

Here it is an example:

var fs = require("fs");
console.log("");
console.log("START");
// Asynchronous read
fs.readFile('myFile1.txt', function (err, data) {
   if (err) {
      return console.error(err);
   }
   console.log("");
   console.log("ASYNCHRONOUS read: " + data.toString());
});
 
// Synchronous read
var fileContent = fs.readFileSync('myFile2.txt');
console.log("SYNCHRONOUS read: " + fileContent.toString());
 
//Get Information from the file/ directory using stat method
fs.stat('myFile1.txt', function (err, info) {
   if (err) {
       return console.error(err);
   }
   console.log("Full information about the file/ directory: ");
   console.log(info);
  
   // Check file type
   console.log("isFile ? " + info.isFile());
   console.log("isDirectory ? " + info.isDirectory());    
});
 
console.log("");
console.log("Program Ended");

When you run the code, you will see:

Now, I have to make some notes:

  • the synchronous task start immediately and is not waiting for the ASYNC task to complete.
  • you can get a lot of information related to a file/ directory and this is done using a callback function in Node.js.