Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

http

node.js

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?

like image 572
Jimmy Z Avatar asked Dec 19 '12 00:12

Jimmy Z


People also ask

What is binary data in HTTP?

If you are using the HTTP connector, you get a choice of what sort of data format to expect. (See below video). Binary format is used for data which you either do not want to parse, or data which cannot be parsed (such as images and executables). All the other formats are parsable.

How do I read a file in node JS?

Node.js as a File Server To include the File System module, use the require() method: var fs = require('fs'); Common use for the File System module: Read files.

What is HTTP method in node JS?

Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP). To include the HTTP module, use the require() method: var http = require('http');


1 Answers

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".

like image 135
Jonathan Lonowski Avatar answered Nov 05 '22 17:11

Jonathan Lonowski