简体   繁体   中英

node.js write http response to stream

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

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.

Thanks in advance & best regards

The callback for http.request only supplies one argument, which is a reference to the response of the request. Try

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

Also note that the ClientResponse implements ReadableStream , so you should use .pipe rather than .socket.pipe .

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);

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM