不能在从响应nodejs发出数据后进行管道连接



我一直在遇到node js的require库的问题。当我尝试管道到文件和流响应时,我得到错误:you cannot pipe after data has been emitted from the response。这是因为我在真正传输数据之前做了一些计算。

的例子:

var request = require('request')
var fs = require('fs')
var through2 = require('through2')
options = {
    url: 'url-to-fetch-a-file'
};
var req = request(options)
req.on('response',function(res){
    //Some computations to remove files potentially
    //These computations take quite somme time.
    //Function that creates path recursively
    createPath(path,function(){
        var file = fs.createWriteStream(path+fname)
        var stream = through2.obj(function (chunk, enc, callback) {
            this.push(chunk)
            callback()
        })
        req.pipe(file)
        req.pipe(stream)
    })
})

如果我只是管道到流而不进行任何计算,就可以了。我怎么能管道到两个文件和流使用request模块在nodejs?

我发现这个:Node.js管道相同的可读流到多个(可写)的目标,但它是不一样的事情。在这里,管道在不同的节拍中发生2次。这个例子用管道输入问题的答案,但仍然收到一个错误。

您可以将侦听器添加到您定义的stream,而不是直接管道到文件。所以你可以用

代替req.pipe(file)
stream.on('data',function(data){
    file.write(data)
})
stream.on('end',function(){
    file.end()
})

stream.pipe(file)

这将暂停流直到它被读取,这在request模块中不会发生。

更多信息:https://github.com/request/request/issues/887

最新更新