Download and save icon using node.js?

I am trying to download an icon from a website using Node.js, but I have some problems.

My code is as follows:

//Imports ... var theurl = http.createClient(80, 'a1.twimg.com'); var requestUrl = 'http://a1.twimg.com/a/1284159889/images/favicon.ico'; var request = theurl.request('GET', requestUrl, {"host": "a1.twimg.com"}); request.end(); request.addListener('response', function (response) { var body = ''; response.addListener('data', function (chunk) { body += chunk; }); response.addListener("end", function() { fs.writeFileSync('favicon.ico', body.toString('binary'), 'binary'); }); }); 

The resulting icon is just rubbish, and I suspect it has something to do with the encoding of the icon when I grab it. What is the right way to do something like this?

+2
source share
2 answers

Try executing the first line in the callback of response.setEncoding('binary') or (since this is not the preferred (by node) encoding) response.setEncoding(null) , which will make it a buffer. And then just write the body directly without doing anything on it.

fs.writeFileSync('favicon.ico', body, 'binary');

+5
source

I had to do response.setEncoding("binary") and provide the third argument to writeFileSync:

 fs.writeFileSync('favicon.ico', body, 'binary') 

This combination worked for me. Thanks.

+1
source

Source: https://habr.com/ru/post/886189/


All Articles