Instructions for the fs.read method in node.js

  • 2020-05-05 10:56:25
  • OfStack

method description:

Reads the file data and writes the buffer object pointed to by buffer according to the specified file descriptor fd. It provides a lower level interface than readFile.

This is generally not recommended for reading files because it requires you to manually manage buffers and file Pointers, which can be a hassle especially if you don't know the file size.

syntax:


fs.read(fd,buffer,offset,length,position,[callback(err,bytesRead,buffer)])

Since this method belongs to the fs module, the fs module (var fs= require(" fs "))

needs to be introduced before use

receive parameters:

fs                       file descriptor

buffer           buffer, data will be written.

offset           buffer write offset

length         (integer)    

position     (integer)     specifies the starting position for the file to be read, and if the entry is null, the data will be read from the position of the current file pointer.

The callback           callback passes three parameters, err, bytesRead, buffer

· err   exception

· bytesRead: number of bytes read

· buffer: buffer object

example:


var fs = require('fs');
fs.open('123.txt' , 'r' , function (err,fd){
 if(err){
  console.error(err);
  return;
 }
 
 var buf = new Buffer(8);
 fs.read(fd, buf, 0, 8, null, function(err,bytesRead, buffer){
  if(err){
   console.log(err);
   return;
  }
  console.log('bytesRead' +bytesRead);
  console.log(buffer);
 })
})

source code:


fs.read = function(fd, buffer, offset, length, position, callback) {
  if (!util.isBuffer(buffer)) {
    // legacy string interface (fd, length, position, encoding, callback)
    var cb = arguments[4],
        encoding = arguments[3];
    assertEncoding(encoding);
    position = arguments[2];
    length = arguments[1];
    buffer = new Buffer(length);
    offset = 0;
    callback = function(err, bytesRead) {
      if (!cb) return;
      var str = (bytesRead > 0) ? buffer.toString(encoding, 0, bytesRead) : '';
      (cb)(err, str, bytesRead);
    };
  }
  function wrapper(err, bytesRead) {
    // Retain a reference to buffer so that it can't be GC'ed too soon.
    callback && callback(err, bytesRead || 0, buffer);
  }
  binding.read(fd, buffer, offset, length, position, wrapper);
};


Related articles: