请注意,我在这里使用间隔来模拟作者是否能够阅读。您可以以任何您想要的方式执行此操作,即如果作者返回 false,您将更新状态以开始缓冲等。我认为最后一行是您想要的,即
r.pipe(b).pipe(w);
内容如下
readStrem.pipe(transformBbuffer).pipe(writeStream);
示例代码,我们可以进行一些更改来缓冲所有数据。我将在代码之后进行描述。您需要了解的有关流的所有信息以及更多信息都在文档中,我认为它们可以使用更完整的示例来完成,但是它们本身就很好...
https://nodejs.org/api/stream.html#stream_class_stream_transform_1
这是代码。
var fs = require('fs');
var stream = require('stream')
const util = require('util');
//const StringDecoder = require('string_decoder').StringDecoder;
const Transform = require('stream').Transform;
var check_buff = 0;
var DRAIN_ME = 0;
var r = fs.createReadStream('file1.txt').setEncoding('utf8');
var w = fs.createWriteStream('file2.txt');
var BufferStream = function () {
stream.Transform.apply(this, arguments);
this.buffer = [];
};
util.inherits(BufferStream, stream.Transform);
var intId;
intId = setInterval(function(){
if(check_buff % 3 == 0) {
DRAIN_ME = 1;
return;
}
DRAIN_ME = 0;
},10);
BufferStream.prototype._transform = function (chunk, encoding, done) {
this.buffer.push(String(chunk));
while(DRAIN_ME > 0 && this.buffer.length > 0) {
this.push(this.buffer.shift());
}
console.log(chunk.length);
console.log(this.buffer.length);
done();
};
var b = new BufferStream();
b.on('end', function(chunk) {
clearInterval(intId);
});
r.pipe(b).pipe(w);
我正在寻找实现转换/直通流的规范方法,该方法会缓冲所有数据,直到调用管道为止。
进行以下更改
BufferStream.prototype._transform = function (chunk, encoding, done) {
this.buffer.push(String(chunk));
console.log(chunk.length);
console.log(this.buffer.length);
done();
};
......
BufferStream.prototype._flush = function (cb) {
var len = this.buffer.length;
for (var i = 0; i < len; i++) {
this.push(this.buffer.shift());
};
cb();
};
您还可以暂停可读流,这实际上会暂停可写流,因为它停止接收数据,即...
要对此进行测试,请在磁盘上创建一个相当大的文件,即 100MB 或更多并运行它...
var fs = require('fs');
var readableStream = fs.createReadStream('file1.txt');
var writableStream = fs.createWriteStream('file2.txt');
readableStream.setEncoding('utf8');
readableStream.on('data', function(chunk) {
var ready = 0;
readableStream.pause();
setInterval(function(){
if(ready == 0) {
//console.log('pausing');
readableStream.pause();
ready = 1;
}
else {
//console.log('resuming');
readableStream.resume();
ready = 0;
}
},100);
writableStream.write(chunk);
});
立即暂停的原因是,在间隔触发10ms
时,文件可能已经被写入。这有一些变化,即......
var fs = require('fs');
var readableStream = fs.createReadStream('file1.txt');
var writableStream = fs.createWriteStream('file2.txt');
readableStream.setEncoding('utf8');
var ready = 0;
setInterval(function(){
if(ready == 0) {
//console.log('pausing');
readableStream.pause();
ready = 1;
}
else {
//console.log('resuming');
readableStream.resume();
ready = 0;
}
},100);
readableStream.on('data', function(chunk) {
writableStream.write(chunk);
readableStream.pause();
});