Method description:
Synchronized version of fs.read() .
The method will return a bytesRead (the number of bytes read)
Grammar:
fs.readSync(fd, buffer, offset, length, position)
Since this method belongs to the fs module, the fs module needs to be introduced before use (var fs= require(“fs”) )
Receive parameters:
fs
buffer The buffer into which data will be written.
offset The offset written to the buffer
length (integer) Specifies the length of the file read in bytes
position (integer) Specifies the starting position of file reading. If this item is null, data will be read starting from the position of the current file pointer.
Example:
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:
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];
};