What are the advantages of synchronous function over asynchronous function in Node.js ?
Last Updated :
31 Mar, 2023
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.
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:
The benefits of synchronous learning:
- Interaction between participants.
- Exchange of knowledge and experience between participants.
- Real-time feedback for the instructor.
- 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
const fs = require("fs");
// Synchronous read
console.log("Synchronous read method:");
const 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
const fs = require("fs");
// Coordinated read
console.log("Synchronous attach method:");
const 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:

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 the fs module in Node.js are:
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:
- Participants can learn in their own time and schedule.
- Less work for trainers and HR managers.
- Automated tasks reduce repetitive work such as giving online classes and grading exams.
- Employees and customers spend less time in a classroom or amphitheater during work hours.
- 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
const 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
const 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:

Similar Reads
How to execute an array of synchronous and asynchronous functions in Node.js?
We have an array of functions, some functions will be synchronous and some will be asynchronous. We will learn how to execute all of them in sequence. Input: listOfFunctions = [ () => { console.log("Synchronous Function); }, async () => new Promise(resolve => { setTimeout(() => { resolve
2 min read
How to Write Asynchronous Function for Node.js ?
The asynchronous function can be written in Node.js using 'async' preceding the function name. The asynchronous function returns an implicit Promise as a result. The async function helps to write promise-based code asynchronously via the event loop. Async functions will always return a value.Await f
2 min read
What is the use of next() function in Express.js ?
Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will discuss, the use of the next() function in every middleware of the express.js.There are
2 min read
How to Return an Array from Async Function in Node.js ?
Asynchronous programming in Node.js is fundamental for handling operations like network requests, file I/O, and database queries without blocking the main thread. One common requirement is to perform multiple asynchronous operations and return their results as an array. This article explores how to
4 min read
How to convert an asynchronous function to return a promise in JavaScript ?
In this article, we will learn how to convert an asynchronous function to return a promise in JavaScript. Approach:Â You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need
3 min read
Difference between Synchronous and Asynchronous Method of fs Module
Asynchronous fs methods in Node.js do not block the event loop and handle multiple operations concurrently, improving performance while Synchronous fs methods block the event loop until the operation completes, which can lead to inefficiencies and slower performance for I/O-bound tasks. Table of Con
5 min read
How to create an Asynchronous function in Javascript?
JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations. Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title
6 min read
Difference Between Synchronous and Asynchronous Action Creators
In web development, Redux has become very popular for managing application state. Action creators play an important role in Redux, which helps the dispatching of actions to update the state. In this article, we will understand the difference between synchronous and asynchronous action creators.What
4 min read
What is the purpose of callback function as an argument of setState event ?
In React, the purpose of callback function as an argument of setState event is to execute the code after the data in the state is modified. Purpose of callback function as an argument of setStateSetState is an asynchronous method. Asynchronous means that the remaining code will get executed while th
2 min read
Difference between synchronous and asynchronous requests in jQuery Ajax
In this article, we'll look at the differences between synchronous and asynchronous JQuery Ajax requests. JQuery provides several built-in methods for requesting data from the server: HTML, TXT, JSON, or String data can be requested. $.ajax() is a popular JQuery method for making synchronous and asy
6 min read