在MyWritableStream中发出错误事件后,数据传输停止.我需要做什么才能恢复数据传输? var readable = fs.createReadStream('test.txt');var writable = new MyWritableStream();writable.on('error', function(error) { console
var readable = fs.createReadStream('test.txt'); var writable = new MyWritableStream(); writable.on('error', function(error) { console.log('error', error); // How i can resume? }); writable.on('finish', function(){ console.log('finished'); }) readable.pipe(writable);我不确定,如果这是正常的做法,但我现在看不到另一个解决方案&这个对我有用.如果您可以提供更准确的解决方案,请执行此操作.
我们可以使用可写入的管道事件跟踪可读的流实例:
function WriteableStream(options) { Writable.call(this, options); this.source = null; var instance = this; this.on('pipe', function(source){ instance.source = source; }); } util.inherits(WriteableStream, Writable);
因此,当我们发出错误事件,并且可读流自动取消时,我们可以自己重新管道:
WriteableStream.prototype._write = function(chunk, encoding, done) { this.emit('error', new Error('test')); // unpipes readable done(); }; WriteableStream.prototype.resume = function() { this.source.pipe(this); // re-pipes readable }
最后,我们将使用以下方式:
var readable = fs.createReadStream(file); var writeable = new WriteableStream(); writeable.on('error', function(error) { console.log('error', error); writeable.resume(); }); readable.pipe(writeable);