Node.js fs open() open and read file

Description

Node.js fs open() open and read file

var fs = require('fs');
var buf = Buffer.alloc(1024);

console.log('Going to open an existing file !');
fs.open('input.txt', 'r+', function(err, fd) {
  if (err) {/*w w  w  .j a  va2s . c om*/
    return console.error(err);
  }
  console.log('File opened Successfully !');
  console.log('Going to read the file');
  fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {
    if (err) {
      console.log(err);
    }
    console.log('File description :' + fd);
    console.log(bytes + ' bytes read');
    
    // Print only reads bytes to avoid junk.
    if (bytes > 0) {
      console.log(buf.slice(0, bytes).toString());
    }
    
    fs.close(fd, function(err) {
      if (err) {
        console.log(err);
      }
      console.log('File closed');
    });
  });
});



PreviousNext

Related