Read File Synchronously and Asynchronously (Blocking and Non-blocking ways)

In this post we will learn to read a text file synchronously with a blocking code and asynchronously by writing non-blocking code.

Node.js provides methods to read a file both synchronously and asynchronously in it’s ‘fs’ module.

Synchronously reading a file using blocking methods of Node.js:

var fs = require('fs');
console.log('Reading the file...');
var contents = fs.readFileSync('test-file.txt','utf8');
console.log(contents);

Asynchronously reading a file using non-blocking methods of Node.js:

var fs = require('fs');
fs.readFile('test-file.txt','utf8', function(error, contents) {
    console.log(contents);
});
console.log('Reading the file...');

Leave a Comment