Skip to content
Related Articles

Related Articles

Improve Article

Difference between synchronous and asynchronous method of fs module

  • Last Updated : 31 Aug, 2021
Geek Week

NodeJS provides us with an inbuilt fs (File System) module for various file handling operations like read a file, write a file, delete a file etc. fs module can be installed using the below statement:

Syntax:

npm install fs --save

Note: The npm in the above command stands for node package manager from where all the dependencies can be installed in NodeJS.

For using the fs module, append the following statement in the code:

const fs = require('fs');

fs module has different operations for file handling such as read files, write files, append files, close files, delete files, etc. All the operations can be performed in a synchronous as well as in an asynchronous approach depending on the user requirements.



1. Synchronous methods: Synchronous functions block the execution of the program until the file operation is performed. These functions are also called blocking functions. The synchronous methods have File Descriptor as the last argument. File Descriptor is a reference to opened files. It is a number or a reference id to the file returned after opening the file using fs.open() method of the fs module. All asynchronous methods can perform synchronously just by appending “Sync” to the function name. Some of the synchronous methods of fs module in NodeJS are:

Example 1: Synchronous read method

Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement:

GeeksForGeeks is a Computer Science portal.

Step 2: Add the following code inside main.js file and execute it:

main.js




var fs = require("fs");
  
// Synchronous read
console.log("Synchronous read method:");
var data = fs.readFileSync('sample.txt');
console.log("Data in the file is - " + data.toString());

Output:

Output of Synchronous Read Method

 



Example 2: Synchronous append method

Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement:

Hello World !

Step 2: Add the following code inside main.js file and execute it:

main.js




var fs = require("fs");
  
// Synchronous read
console.log("Synchronous append method:");
  
var data = "\nGeeksForGeeks is a Computer Science portal.";
  
// Append data to file
fs.appendFileSync('sample.txt', data, 'utf8');
console.log("Data is appended to file successfully.")
  
data = fs.readFileSync('sample.txt');
console.log("Data in the file after appending is - \n" + data.toString());

Output:

Output of Synchronous Append Method

2. Asynchronous methods:

Asynchronous functions do not block the execution of the program and each command is executed after the previous command even if the previous command has not computed the result. The previous command runs in the background and loads the result once it has finished processing. Thus, these functions are called non-blocking functions. They take a callback function as the last parameter. Asynchronous functions are generally preferred over synchronous functions as they do not block the execution of the program whereas synchronous functions block the execution of the program until it has finished processing. Some of the asynchronous methods of fs module in NodeJS are:

Heavy operations which consume time for processing such as querying huge data from a database should be done asynchronously as other operations can still be executed and thus, reducing the time of execution of the program.

Example 1: Asynchronous read method

Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement: 



GeeksForGeeks is a Computer Science portal.

Step 2: Add the following code inside main.js file and execute it:

main.js




var fs = require("fs");
    
// Asynchronous read
console.log("Asynchronous read method:");
fs.readFile('sample.txt', function (err, data) {
   if (err) {
      return console.error(err);
   }
   console.log("Data in the file is - " + data.toString());
});

Output:

Output of Asynchronous Read Method

Example 2: Asynchronous append method

Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement:

Hello World !

Step 2: Add the following code inside main.js file and execute it:

main.js




var fs = require("fs");
  
const data = "\nGeeksForGeeks is a Computer Science portal.";
     
// Asynchronously appending data to file
fs.appendFile('sample.txt', data, 'utf8',
    
    // Callback function
    function(err) { 
        if (err) throw err;
    
        //  If no error
        console.log("Data is appended to file successfully.")
});
  
fs.readFile('sample.txt', function (err, data) {
    if (err) {
       return console.error(err);
    }
    console.log("Data in the file after appending: \n"
        + data.toString());
 });

Output:

Output of Asynchronous Append Method

Difference between Asynchronous and Synchronous methods:

Sr.no

Synchronous methods

Asynchronous methods

1.Synchronous functions are called blocking functionsAsynchronous functions are called non-blocking functions.
2.It blocks the execution of the program until the file operation has finished processing.It does not block the execution of the program.
3.These functions take File Descriptor as the last argument.These functions take a callback function as the last argument.
4.Examples: fs.readFileSync(), fs.appendFileSync(), fs.writeFileSync() etc.Examples: fs.readFile(), fs.appendFile(), fs.writeFile(), fs.stat() etc.                                                               



My Personal Notes arrow_drop_up
Recommended Articles
Page :