Description of the fs. readSync method in node. js, node. jsfs. readsync
Method description:
Synchronous version of fs. read ().
Method returns a bytesRead (number of bytes read)
Syntax:
Copy codeThe Code is as follows:
Fs. readSync (fd, buffer, offset, length, position)
Because this method belongs to the fs module, we need to introduce the fs module (var fs = require ("fs") before use "))
Receiving parameters:
Fs
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.
Example:
Copy codeThe 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 );
Var readfile = fs. readSync (fd, buf, 0, 8, null );
Console. log (readfile );
})
Source code:
Copy codeThe Code is as follows:
Fs. readSync = function (fd, buffer, offset, length, position ){
Var legacy = false;
If (! Util. isBuffer (buffer )){
// Legacy string interface (fd, length, position, encoding, callback)
Legacy = true;
Var encoding = arguments [3];
AssertEncoding (encoding );
Position = arguments [2];
Length = arguments [1];
Buffer = new Buffer (length );
Offset = 0;
}
Var r = binding. read (fd, buffer, offset, length, position );
If (! Legacy ){
Return r;
}
Var str = (r> 0 )? Buffer. toString (encoding, 0, r ):'';
Return [str, r];
};