How we can read a file in Node JS?

Syntax of read a file is given below:-

fs.read(fd, buffer, offset, length, position, callback)


                                        var fs = require("fs");
var buf = new Buffer(1024);

console.log("open existing file");
fs.open('file.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   console.log("File opened");
   console.log("read the file");
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
      console.log(bytes + " bytes read");

      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());

Suggest An Answer

No suggestions avaliable!

Related Interview Questions