Jimmy Z
Jimmy Z

Reputation: 743

How do I read a binary file via HTTP in node?

I have an image on a web server (http://example.com/img.jpg). I open that image in a browser and save it to disk.

If I open the file in node via the 'fs' module (fs.readFileSync), I get a Buffer that begins with 0xff, which is what I would expect.

I'd like to be able to get the same result directly from an HTTP request. I'm using the 'request' module to make the request.

request('http://example.com/img.jpg',function(error, response, body){
  //code here
});

I can't figure out how to turn the response or body into an equivalent Buffer from what I'm getting from the FileSystem. What am I missing?

Upvotes: 5

Views: 2111

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

You can get a Buffer by setting the encoding to null:

request('http://example.com/img.jpg', { encoding: null }, function(error, response, body){
  console.log(Buffer.isBuffer(body)); // true
});

request treats any other value as an argument for buffer.toString(), which defaults undefined to "utf8".

Upvotes: 5

Related Questions