【发布时间】: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 流中读取。如果没有,我将重新提出问题。
-
请求是获取文件。写入文件的位置具有有限的大小,并且文件的大小是事先知道的。计算会删除将写入文件的目录中最旧的文件,直到文件适合该位置。