Save a binary file using REQUEST module in Node the right way

I was trying to save some PDF from an output of a request, and I always got a corrupted file.

Initially I found that I saved my file as UTF-8 while it was ascii (took almost double), so I added the ASCII encoding to the file fs,fileWrite command, this helped a bit but still corrupted.

Eventually I read some more about the request module and identified that i was missing the "encoding: 'binary'" in the options!

This is the final code:
SaveThePDF(url, filename) {
const writeFile = denodeify(fs.writeFile);
const requestPromised = denodeify(request.defaults({
'gzip': true,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*\/*;q=0.8',
}
}), function(err, httpResponse, body) {
// Convert 3 paramters to 2
return [err, {httpResponse: httpResponse, body: body}];
});
return requestPromised({
url: url,
method: 'post',
encoding: 'binary'
}).then ( (response) => {
return writeFile(filename, response.body, 'ascii');
});
}


Save a binary file using REQUEST module in Node the right way Save a binary file using REQUEST module in Node the right way Reviewed by Ran Davidovitz on 11:13 AM Rating: 5

No comments:

Powered by Blogger.