Method description:
Synchronous version of fs.read().
The method will return a bytesRead (number of bytes read)
grammar:
The code copy is as follows:
fs.readSync(fd, buffer, offset, length, position)
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
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.
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);
var readfile = fs.readSync(fd, buf, 0, 8, null);
console.log(readfile);
})
Source code:
The code copy 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];
};