如何使用node.js加载和保存图像?

有这样的代码:

var http = require('http'); var fs = require('fs'); var data; var options = { host: 'nodejs.org', port: 80, path: '/images/logo.png', method: 'GET' }; var req = http.request(options, function(res) { res.on('data', function (chunk) { data += chunk; }); res.on('end', function () { fs.writeFile('1.png', data, function (err) { if(err) console.log('NNOOOOOOOOOOOO'); }); }); }); req.on('error', function(e) { console.log('error: ' + e.message); }); req.end(); 

这个脚本创build文件1.png并保存获得的数据,但我无法在Windows中打开它。

请帮忙。

你可以这样做 :

 var req = http.request(options, function(res) { var file = fs.createWriteStream('1.png'); res.pipe(file); }); req.on('error', function(e) { console.log('error: ' + e.message); }); req.end(); 

更新

我检查了你的代码,发现了两件事情:

  1. data未正确初始化。
  2. 使用setEncoding将响应视为二进制。 不需要在writeFile指定编码

所以只需在http.requestcallback的开头添加这两行:

  res.setEncoding("binary") ; var data=''; 

那么你的代码应该工作正常。

您需要设置正确的编码。

 res.setEncoding('binary') fs.writeFile('1.png', data, {encoding: 'binary'}, function(err){