Node js read file example; In this tutorial guide, You will learn how to read file (text, HTML, etc) from the system server using node js. And as well as, This tutorial provides you to the example of reading file data in asynchronous (non-blocking) and synchronous (blocking).
You can read a file in NodeJS using fs module. And can read file in synchronous and asynchronous mode using readFile() and readFileSync() methods.
How to Read a File in Node JS
There are two functions to read files in the node js. First function readFile() and another function is readFileSync(). The first function reads the data of the file asynchronous. The second function reads the file’s data synchronously.
- readFile() function
- readFileSync() function
readFile() function
The readFile () function reads the file’s data asynchronous.
syntax
fs.readFile(file[, options], callback)
Example – Node JS Read file in asynchronously
var fs = require('fs'); fs.readFile('c:\\myfile.txt', 'utf8', function(error, data) { if (error) { console.log('Error:- ' + error); throw error; } console.log(data); });
readFileSync() function
The readFileSync() function reads the file’s data Synchronous.
syntax
fs.readFileSync(file[, options])
Example – Node JS Read file in synchronously
var fs = require('fs'); var data = fs.readFileSync('c:\\myfile.txt', 'utf8'); console.log(data);
Note:- Both fs.readFile () and fs.readFileSync () read the entire contents of the given files into memory before returning data.