Download and save a favicon with node.js?

Tag: node.js Author: honda123 Date: 2010-08-26

I'm trying to download a favicon from a website using Node.js, but am having some trouble.

My code is as follows:

//Imports ...

var theurl = http.createClient(80, '');
var requestUrl = '';
var request = theurl.request('GET', requestUrl, {"host": ""});

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 garbage, however, and I suspect it has something to do with the encoding of the favicon when I grab it this way. What's the correct way to do something like this?

Best Answer

Try as a first line in the response callback response.setEncoding('binary'), or (since that's not a preferred (by node) encoding to set) response.setEncoding(null), which will make it a Buffer. And then just write body directly, without performing anything on it.

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


Didn't work with response.setEncoding(null), but did work with response.setEncoding('binary').
@jimt - did you also try with null and then skip the third argument in the write? So that it's fs.wFS('favicon', body);

Other Answer1

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.