Javascript node.js 将 http 响应写入流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11906198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:37:27  来源:igfitidea点击:

node.js write http response to stream

javascripthttpnode.jsstreamrequest

提问by senorpedro

i'm fetching some binary data over http. My code looks like:

我正在通过 http 获取一些二进制数据。我的代码看起来像:

var writeStream = fs.createWriteStream(fileName);
request(url, function(err, res) {
    res.socket.pipe(writeStream);
});

now the output file is created but the filesize is 0. The url is correct though, i verified that with wget.

现在创建了输出文件,但文件大小为 0。虽然 url 是正确的,但我用 wget 验证了这一点。

Thanks in advance & best regards

提前致谢并致以最诚挚的问候

回答by bkconrad

The callback for http.requestonly supplies one argument, which is a reference to the responseof the request. Try

的回调http.request仅提供一个参数,即对请求响应的引用。尝试

http.request(url, function(res) {
    res.pipe(writeStream);
});

Also note that the ClientResponseimplements ReadableStream, so you should use .piperather than .socket.pipe.

还要注意ClientResponse工具ReadableStream,所以你应该使用.pipe而不是.socket.pipe.

回答by ebohlman

I'm assuming that here requestis from mikeal's request library rather than being an instance of http.request. In that case you can simply do request(url).pipe(writeStream);

我假设这里request来自 mikeal 的请求库而不是http.request. 在这种情况下,你可以简单地做request(url).pipe(writeStream);

Remember that for debugging purposes, you can always pipe to process.stdout.

请记住,出于调试目的,您始终可以通过管道连接到process.stdout.

回答by Udhaya

var readStream = fs.createReadStream(fileName);
request(url, function(err, res) {
  readStream.pipe(res);
  readStream.on('end', function() {
    //res.end({"status":"Completed"});
  });
});