This article mainly introduces node. fs. description of the read method. This article introduces the fs. read method description, syntax, receive parameters, use instances, and implement Source Code. For more information, see
Method description:
Reads file data based on the specified file descriptor fd and writes it to the buffer object pointed to by the buffer. Compared with readFile, it provides a more underlying interface.
Generally, this method is not recommended to read files because it requires you to manually manage the buffer and file pointer, especially when you do not know the file size, this will be a very troublesome task.
Syntax:
The Code is as follows:
Fs. read (fd, buffer, offset, length, position, [callback (err, bytesRead, buffer)])
Because this method belongs to the fs module, we need to introduce the fs module (var fs = require ("fs") before use "))
Receiving parameters:
Fs file descriptor
Buffer, data will be written.
Offset buffer write offset
Length (integer) specifies the length of the number of bytes that the file reads.
Position (integer) specifies the start position of File Reading. If this parameter is set to null, data is read from the current file pointer.
The callback passes three parameters: err, bytesRead, and buffer.
· Err exception
· BytesRead: number of bytes read
· Buffer: buffer object
Example:
The Code 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 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 );
};