To read the file (text, HTML, JSON, etc) from the system or server using node js, you can do it in two ways first asynchronous (non-blocking) and second synchronous (blocking).
You can read a file in NodeJS using fs
the module, and can also read files in synchronous and asynchronous mode using readFile() and readFileSync() methods.
How to Read a File in Node JS
Here are two ways to read files (text, HTML, JSON, etc) in Node js:
1. readFile() function
The readFile()
function reads the file’s data asynchronous or async. it means the readFile()
method does not block the execution of the next program until the first program is completed.
Here is the basic syntax:
fs.readFile(file[, options], callback)
Here is the code to read file using readFile function in node js:
The following code reads the file abc.txt
asynchronously and prints its contents to the console:
var fs = require('fs'); fs.readFile('c:\\abc.txt', 'utf8', function(error, data) { if (error) { console.log('Error:- ' + error); throw error; } console.log(data); });
2. readFileSync() function
The readFileSync()
function reads the file’s data Synchronous or sync. It means reafileSync()
method blocks the execution of the next program until the first program is completed.
Here is the basic syntax:
fs.readFileSync(file[, options])
Here is the code to read file using readFileSync function in node js:
The following code reads the file abc.txt
synchronously and prints its contents to the console:
var fs = require('fs'); var data = fs.readFileSync('c:\\myfile.txt', 'utf8'); console.log(data);
If you use asynchronous method in node JS to read file, you can read data from file in less time than synchronous method.
Conclusion
Both fs.readFile()
and fs.readFileSync()
read the entire contents of the given files into memory before returning data.