Method description:
Read file data according to the specified file descriptor fd and write to the buffer object pointed to by the buffer. It provides a more underlying interface than readFile.
This method is generally not recommended to read files because it requires you to manually manage buffers and file pointers, especially when you don't know the file size, which can be a very troublesome thing.
grammar:
The code copy is as follows:
fs.read(fd,buffer,offset,length,position,[callback(err,bytesRead,buffer)])
Since this method belongs to the fs module, it is necessary to introduce the fs module before use (var fs= require("fs") )
Receive parameters:
fs file descriptor
buffer, data will be written.
offset write to offset buffer
length (integer) Specifies the length of the file reading bytes
position (integer) Specifies the starting position for file reading. If this item is null, data will be read from the position of the current file pointer.
The callback passes three parameters, err, bytesRead, and buffer
・ err exception
・ bytesRead: the number of bytes read
・buffer:buffer object
example:
The code copy is as follows:
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:
The code copy is as follows:
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);
};