22

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

3 Answers 3

26

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.

Sign up to request clarification or add additional context in comments.

2 Comments

const req = http.request... and then req.end() in order to make it work
pipe is extremely slow
7

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.

1 Comment

What is the difference if you are using the node core https library, and not the library you mentioned?
3

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

1 Comment

you can only pipe a readable to a writable, not the opposite like you suggest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.