Node.js ReadStream:内部缓冲区不再填满
我有一个fs.ReadStream对象,它指向一个相当大的文件。现在我想从ReadStream读取8000字节,但是内部缓冲区只有6000字节。因此,我的方法是读取这6000字节,然后使用while循环检查内部缓冲区长度是否不再为0,等待内部缓冲区再次填满 大概是这样的:Node.js ReadStream:内部缓冲区不再填满,node.js,stream,buffer,Node.js,Stream,Buffer,我有一个fs.ReadStream对象,它指向一个相当大的文件。现在我想从ReadStream读取8000字节,但是内部缓冲区只有6000字节。因此,我的方法是读取这6000字节,然后使用while循环检查内部缓冲区长度是否不再为0,等待内部缓冲区再次填满 大概是这样的: BinaryObject.prototype.read = function(length) { var value; // Check whether we have enough data in the inte
BinaryObject.prototype.read = function(length) {
var value;
// Check whether we have enough data in the internal buffer
if (this.stream._readableState.length < length) {
// Not enough data - read the full internal buffer to
// force the ReadStream to fill it again.
value = this.read(this.stream._readableState.length);
while (this.stream._readableState.length === 0) {
// Wait...?
}
// We should have some more data in the internal buffer
// here... Read the rest and add it to our `value` buffer
// ... something like this:
//
// value.push(this.stream.read(length - value.length))
// return value
} else {
value = this.stream.read(length);
this.stream.position += length;
return value;
}
};
BinaryObject.prototype.read=函数(长度){
var值;
//检查内部缓冲区中是否有足够的数据
if(this.stream.\u readableState.length
问题是,缓冲区不再被填满——脚本将在while循环中空闲
最好的方法是什么?非常简单。您不需要在您的一侧执行任何缓冲:
var fs = require('fs'),
rs = fs.createReadStream('/path/to/file');
var CHUNK_SIZE = 8192;
rs.on('readable', function () {
var chunk;
while (null !== (chunk = rs.read(CHUNK_SIZE))) {
console.log('got %d bytes of data', chunk.length);
}
});
rs.on('end', function () {
console.log('end');
});
如果CHUNK\u SIZE
大于内部缓冲区,则节点将返回null并在再次发出readable
之前再缓冲一些。您甚至可以通过传递以下信息来配置缓冲区的初始大小:
var rs = fs.createReadStream('/path/to/file', {highWatermark: CHUNK_SIZE});
下面是在流中读取文件的示例
var fs = require('fs'),
readStream = fs.createReadStream(srcPath);
readStream.on('data', function (chunk) {
console.log('got %d bytes of data', chunk.length);
});
readStream.on('readable', function () {
var chunk;
while (null !== (chunk = readStream.read())) {
console.log('got %d bytes of data', chunk.length);
}
});
readStream.on('end', function () {
console.log('got all bytes of data');
});
你能告诉我在我的环境下会是什么样子吗?我希望有一个方法(BinaryObject#read(int-length))返回一个缓冲区,无论内部缓冲区现在保存了多少数据。在缓冲区可用之前,您无法阻止,因为node.js在设计上是异步的。