This guide will elaborate on how to read a file synchronously with the fs.readFileSync() method in Node.js.
Sample File
An HTML file is created as a sample in the Node.js project that contains the following content:
Note: The entire content of the above sample file will read synchronously with the Node.js “fs.readFileSync()” method.
How to Read File Synchronously with fs.readFileSync() in Node.js?
The “fs.readFileSync()” is a pre-defined method that reads the file in a synchronous way by blocking all other parallel processes. It stops the execution of the original node program until the defined task is completed i.e. reading the file completely. Once the reading of a file is done, then the remaining node program will start executing.
Syntax
Here is the basic syntax to use the “fs.readFileSync()” method:
The above syntax takes two parameters:
- path: It specifies the path of the sample file. It can be the relative address or the URL. If the specified file is avialable in the current directory of the node then use only the file name in double/single quotes.
- options: It is an optional parameter that supports two options:
- encoding: It holds the encoding type i.e. “utf8” otherwise its default value is “null”.
- flag: It indicates the operation performed on the specified file. Its default value is “r”.
Now, use the above-defined method practically with the help of the following code block:
try {
const data = fs.readFileSync('index.html', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
In the above code lines:
- Firstly, the “fs” variable includes the File System(fs) module with the help of the “require()” method.
- Next, the “try” statement defines a code block that applies the “readFileSync()” to read the specified file content and then display its “data” using the “conolsol.log()” method.
- If an error is generated, the “catch” statement will execute the “console.error()” method to display an error message.
Note: Add the above lines of code in the newly created “.js” file. For instance, its name is “app.js”:
Save(Ctrl+S) and close(Ctrl+X) the above file.
Output
Now, execute the below-stated command to run the “.js” file:
The terminal shows the specified file content successfully:
That’s all about reading a file synchronously with the “fs.readFileSync()” method.
Conclusion
In Node.js, to read a file synchronously, use the inbuilt “fs.readFileSync()” method. The working of this method relies on its basic syntax that works on two parameters “path” and “options”. It blocks the execution of all other processes and only performs the reading of the specified file. This guide has elaborated on reading a file synchronously with the fs.readFileSync() method in Node.js.