更新
去年接受的答案还不错,但现在我会使用其他人都在用的软件包: https://github.com/mikeal/request
原始内容
我正在尝试使用node.js抓取谷歌的标志并将其保存到我的服务器上。
这是我现在拥有的代码,但它不起作用:
var options = {
host: 'google.com',
port: 80,
path: '/images/logos/ps_logo2.png'
};
var request = http.get(options);
request.on('response', function (res) {
res.on('data', function (chunk) {
fs.writeFile(dir+'image.png', chunk, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
});
我该怎样让它正常工作?
.setEncoding('binary')
,而应该使用res.pipe(fs.createWriteStream())
来代替在内存中缓冲整个图像。如果你懒得自己做,可以使用这个库:https://github.com/stream-utils/save-to - Jonathan Ong