How Node js read the content of a file?

devquora
devquora

Posted On: Feb 22, 2018

 

Normally NodeJs reads the content of a file in non-blocking, asynchronous way. Node Js uses its fs core API to deal with files. The easiest way to read the entire content of a file in nodeJs is with fs.readFile method. Below is sample code to read a file in NodeJs asynchronously and synchronously.

Reading a file in node asynchronously/ non-blocking

var fs = require('fs'); 
fs.readFile('DATA', 'utf8', function(err, contents) {
    console.log(contents);
});
console.log('after calling readFile');

Reading a file in node asynchronously/blocking

var fs = require('fs'); 
var contents = fs.readFileSync('DATA', 'utf8');
console.log(contents);

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Node JS Interview Questions with Express

    What is Node js ?

    Node Js is one of the most popular and powerful server technologies today. It allows you built the entire website only..

    Node JS Interview Questions with Express

    Explain CLI in Node.js?

    CLI stands for Command Line Interface. It is a utility or program on your computer where users type commands to perform..

    Node JS Interview Questions with Express

    In which Language Node Js is written ?

    Node js is written in C, C++,JavaScript.It uses Google’s open source V8 Javascript Engine to convert Javascript code..