Skip to content
Related Articles

Related Articles

What are the advantages of synchronous function over asynchronous function in Node.js ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 01 Apr, 2022

Node.js furnishes us with an inbuilt fs (File System) module for different documents taking care of tasks like reading a record, composing a document, erasing a document, and so on. fs module can be introduced utilizing the underneath explanation:

Syntax:

npm introduce fs --save

Note: The npm in the above order represents the hub bundle supervisor from where every one of the conditions can be introduced in Node.js.

For utilizing the fs module, annex the accompanying assertion in the code:

const fs = require('fs');

fs module has various tasks for document dealing like reading records, composing documents, affixing documents, closing documents, erasing records, and so on. Every one of the activities can be acted in a coordinated as well as in a nonconcurrent approach contingent upon the client’s prerequisites.

1. Synchronous Methods: Synchronous capacities block the execution of the program until the document activity is performed. These capacities are additionally called hindering capacities. The simultaneous techniques have File Descriptor as the last contention. Document Descriptor is a reference to opened records. It is a number or a reference id to the document returned in the wake of opening the record utilizing fs.open() strategy for the fs module. Everything offbeat technique can be performed simultaneously by annexing “Sync” to the capacity name. A portion of the simultaneous techniques for fs module in Node.js are:

  • fs.readFileSync() method
  • fs.renameSync() method
  • fs.writeSync() method
  • fs.writeFileSync() method
  • fs.fsyncSync() method
  • fs.appendFileSync() method
  • fs.statSync() method
  • fs.readdirSync() method
  • fs.existsSync() method

The benefits of synchronous learning:

  1. Interaction between participants.
  2. Exchange of knowledge and experience between participants.
  3. Real-time feedback for the instructor.
  4. Training happens on a fixed schedule.

Example 1: Synchronous read technique:

Let’s make a JavaScript record named main.js and a text document with the name sample.txt having the accompanying assertion:

GeeksForGeeks is a Computer Science portal.

Add the accompanying code inside the main.js record and execute it:

Javascript




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

Output:

Example 2: Synchronous attach strategy

Let’s make a JavaScript record named main.js and a text document with the name sample.txt having the accompanying assertion:

Hi World !

Add the accompanying code inside the main.js record and execute it:

Javascript




var fs = require("fs");
 
// Coordinated read
console.log("Synchronous attach method:");
var information = "\nGeeksForGeeks is a Computer Science entrance.";
 
// Attach information to record
fs.appendFileSync('sample.txt', information, 'utf8');
console.log("Data is attached to record effectively.")
information = fs.readFileSync('sample.txt');
console.log("Data in the record subsequent to adding is - \n" +
data.toString());

 Output:

2. Asynchronous methods: Asynchronous functions don’t impede the execution of the program and each order is executed after the past order regardless of whether the past order has not registered the outcome. The past order runs behind the scenes and burdens the outcome whenever it has gotten done with handling. Consequently, these capacities are called non-impeding capacities. They accept a callback work as the last boundary. Asynchronous functions are by and large liked over simultaneous capacities as they don’t obstruct the execution of the program while coordinated capacities block the execution of the program until it has gotten done with handling. A portion of the nonconcurrent strategies for fs module in Node.js are:

  • fs.readFile() method
  • fs.rename()  method
  • fs.write() method
  • fs.writeFile() method
  • fs.fsync() method
  • fs.appendFile() method
  • fs.stat() method
  • fs.readdir() method
  • fs.exists() method

Weighty tasks which consume time for handling. For example, questioning colossal information from a data set ought to be done asynchronously as different activities can, in any case, be executed and in this manner, lessening the hour of execution of the program.

The benefits of asynchronous learning:

  1. Participants can learn in their own time and schedule.
  2. Less work for trainers and HR managers.
  3. Automated tasks reduce repetitive work such as giving online classes and grading exams.
  4. Employees and customers spend less time in a classroom or amphitheater during work hours.
  5. There is no real-time interaction with other people.

Example1: Asynchronous read technique

Stage 1: Let’s make a JavaScript document named main.js and a text record with the name sample.txt having the accompanying assertion:

GeeksForGeeks is a Computer Science portal.

Stage 2: Add the accompanying code inside the main.js record and execute it:

Javascript




var fs = require("fs");
 
// Offbeat read
console.log("Asynchronous read method:");
fs.readFile('sample.txt', work(blunder, information){
    in the event that(blunder) {
        return console.error(err);
    }
  console.log("Data in the document is - "
      + data.toString());
});   

Output:

Example 2: Asynchronous annex technique

Stage 1: Let’s make a JavaScript document named main.js and a text record with the name sample.txt having the accompanying assertion:

Hi World !

Stage 2: Add the accompanying code inside the main.js record and execute it:

Javascript




var fs = require("fs");
const information =
    "\nGeeksForGeeks is a Computer Science entrance.";
 
// Asynchronously attaching information to document
fs.appendFile('sample.txt', information, 'utf8',
 
    // Callback work
    function (err) { 
   
          // In event that(fail) toss blunder
        // In the event that no mistake
        console.log("Data is added to document effectively.")
    });
    fs.readFile('sample.txt', work(fail, information) {
        if(fail) {
            return console.error(err);
        
    console.log(
        "Data in the record in the wake of affixing: \n" +
        data.toString()
    );
});   

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!