Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js write http response to stream

Tags:

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

like image 276
senorpedro Avatar asked Aug 10 '12 17:08

senorpedro


People also ask

What is HTTP response stream?

HTTP Streaming is a push-style data transfer technique that allows a web server to continuously send data to a client over a single HTTP connection that remains open indefinitely.

How do I send a response in node JS?

Methods to send response from server to client are:Using send() function. Using json() function.

What is HTTP streaming in node JS?

Streams are one of the fundamental concepts that power Node. js applications. They are data-handling method and are used to read or write input into output sequentially. Streams are a way to handle reading/writing files, network communications, or any kind of end-to-end information exchange in an efficient way.


1 Answers

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.

like image 136
bkconrad Avatar answered Sep 21 '22 03:09

bkconrad