开发者

Download and save a favicon with node.js?

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 theu开发者_运维问答rl = 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 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?


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');


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜