Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting binary content in node.js with http.request

I would like to retrieve binary data from an https request.

I found a similar question that uses the request method, Getting binary content in Node.js using request, is says setting encoding to null should work, but it doesn't.

options = {     hostname: urloptions.hostname,     path: urloptions.path,     method: 'GET',     rejectUnauthorized: false,     encoding: null };  req = https.request(options, function(res) {     var data;     data = "";     res.on('data', function(chunk) {         return data += chunk;     });     res.on('end', function() {         return loadFile(data);     });     res.on('error', function(err) {         console.log("Error during HTTP request");         console.log(err.message);     }); }) 

Edit: setting encoding to 'binary' doesn't work either

like image 357
edi9999 Avatar asked Jul 24 '13 14:07

edi9999


People also ask

Can HTTP transfer binary files?

HTTP is perfectly capable of handling binary data: images are sent over HTTP all the time, and they're binary. People upload and download files of arbitrary data types all the time with no problem.

Do node js servers block on HTTP requests?

Your code is non-blocking because it uses non-blocking I/O with the request() function. This means that node. js is free to service other requests while your series of http requests is being fetched.


Video Answer


1 Answers

The accepted answer did not work for me (i.e., setting encoding to binary), even the user who asked the question mentioned it did not work.

Here's what worked for me, taken from: http://chad.pantherdev.com/node-js-binary-http-streams/

http.get(url.parse('http://myserver.com:9999/package'), function(res) {     var data = [];      res.on('data', function(chunk) {         data.push(chunk);     }).on('end', function() {         //at this point data is an array of Buffers         //so Buffer.concat() can make us a new Buffer         //of all of them together         var buffer = Buffer.concat(data);         console.log(buffer.toString('base64'));     }); }); 

Edit: Update answer following a suggestion by Semicolon

like image 78
Guaycuru Avatar answered Sep 20 '22 14:09

Guaycuru