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
node.js write http response to stream
提问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.request
only 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 ClientResponse
implements ReadableStream
, so you should use .pipe
rather than .socket.pipe
.
还要注意ClientResponse
工具ReadableStream
,所以你应该使用.pipe
而不是.socket.pipe
.
回答by ebohlman
I'm assuming that here request
is 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"});
});
});