【问题标题】:Cannot pipe after data has been emitted from the response nodejs从响应nodejs发出数据后无法管道
【发布时间】:2023-03-21 02:54:01
【问题描述】:

我在使用 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)
    })
})

如果我只是通过管道传输到流而不进行任何计算,那很好。如何使用 nodejs 中的request 模块通过管道传输到文件和流?

我找到了这个:Node.js Piping the same readable stream into multiple (writable) targets,但它不是一回事。在那里,管道在不同的滴答声中发生 2 次。这个例子就像问题中的答案一样管道,但仍然收到错误。

【问题讨论】:

  • 这不一样吗?
  • 在流中,您不能重用管道数据。您在寻找 pub-sub 架构吗?
  • 你能告诉计算中发生了什么吗,它是否涉及从 req 流中读取。如果没有,我将重新提出问题。
  • 请求是获取文件。写入文件的位置具有有限的大小,并且文件的大小是事先知道的。计算会删除将写入文件的目录中最旧的文件,直到文件适合该位置。

标签: node.js pipe


【解决方案1】:

您可以将侦听器添加到您定义的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

【讨论】:

  • 所以你的意思是将响应传递给流然后提交问题?那为什么不做stream.pipe(file)。你写的就是这样。
  • 你说的很对,我来编辑。但我仍然认为这是一个有用的问题......
猜你喜欢
  • 1970-01-01
  • 2019-10-10
  • 2022-01-03
  • 1970-01-01
  • 2021-11-06
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
相关资源
最近更新 更多