【发布时间】:2016-05-08 21:30:57
【问题描述】:
我在 JavaScript 中创建了一个从 URL 下载图像并将图像写入磁盘的函数。该功能适用于我下载的大多数图像,但是有 30 个左右(共 400 个)已损坏且无法打开。文件已创建,但没有关联扩展名,详细信息显示该文件为 0 kB。我知道源文件没有损坏,因为我在 C# 中有一个适用于所有文件的有效解决方案。
var download = function(url, destination, callback) {
fs.exists(destination, function(exists){
if (!exists){
http.get(url, function(response) {
var imageData = '';
response.setEncoding('binary');
response.on('data', function(chunk){
imageData += chunk;
});
response.on('end', function(){
fs.writeFile(destination, imageData, 'binary', function(error){
if(error){
console.log(error);
} else{
callback();
}
});
});
});
}
});
};
我正在使用 Windows 机器,不确定这是否会成为问题,所以我想我会提到它。
【问题讨论】:
-
FWIW 您可以简单地使用
response.pipe(fs.createWriteStream(destination)).on('finish', callback);流式传输文件,而不是缓冲整个文件并使用fs.writeFile()。 -
尝试this answer 使用缓冲区数组的替代方法。