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.
w3wiki is a Computer Science portal.
Step 2: Add the following code inside main.js file and execute it:
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:
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.
var fs = require("fs");
// Synchronous read
console.log("Synchronous append method:");
var data = "\nw3wiki 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:
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 Content
- FS Module in Node
- Synchronous Methods
- Asynchronous Methods
- Difference between Asynchronous and Synchronous methods
- When to Use Each