Home > Web Front-end > JS Tutorial > Instructions for using the fs.read method in node.js_node.js

Instructions for using the fs.read method in node.js_node.js

WBOY
Release: 2016-05-16 16:26:11
Original
1333 people have browsed it

Method description:

Read file data based on the specified file descriptor fd and write the buffer object pointed to by buffer. It provides a lower-level interface than readFile.

It is generally not recommended to use this method 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 thing .

Grammar:

Copy code The code is as follows:

fs.read(fd,buffer,offset,length,position,[callback(err,bytesRead,buffer)])

Since this method belongs to the fs module, the fs module needs to be introduced before use (var fs= require(“fs”) )

Receive parameters:

fs File descriptor

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.

callback The callback passes three parameters, err, bytesRead, buffer

· err Exception

· bytesRead: Number of bytes read

·buffer: buffer object

Example:

Copy code 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:

Copy 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);
};
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template