在写完成之前管道的节点流

时间:2016-04-29 22:15:08

标签: node.js asynchronous

我的缓冲流在完成写入'响应之前就已经被管道传输了.Body'投入此错误: Error: write after end at writeAfterEnd

var bufferStream = new stream.PassThrough();
bufferStream.end(response.Body);
        var stream = bufferStream.pipe(fs.createWriteStream(dlFile));
            stream.on('finish', function () {
                console.log('finished writing stream');
                cb(null, response);
            });

我无法使用该活动'结束'因为它是PassThrough流。如何确保第一个过程完成?

1 个答案:

答案 0 :(得分:1)

您应该在将数据传输到可写流之后编写数据。那是bufferStream.pipe行应该在bufferStream.end行之前:

var bufferStream = new stream.PassThrough();    
// pipe first
var stream = bufferStream.pipe(fs.createWriteStream(dlFile))
  .on('finish', function () {
    console.log('finished writing stream');
    cb(null, response);
  });
//now write data
bufferStream.end(response.Body);