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
You need to set encoding to response, not request:
Here is useful answer: Writing image to local server
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/
Edit: Update answer following a suggestion by Semicolon
Running on NodeJS 6.10 in the AWS Lambda environment, none of the solutions above worker for me.
What did work for me was the following:
Take note the res.setEncoding('binary'); and Buffer.from(chunk, 'binary') lines. One sets the response encoding and the other creates a Buffer object from the string provided in the encoding specified previously.