Javascript 使用节点js下载不完整/部分图像
我正在以标准方式使用node js从站点下载图像Javascript 使用节点js下载不完整/部分图像,javascript,node.js,Javascript,Node.js,我正在以标准方式使用node js从站点下载图像 var download = function (uri, filename, callback) { request.head(uri, function (err, res, body) { console.log('content-type:', res.headers['content-type']); console.log('content-length:', res.headers['cont
var download = function (uri, filename, callback) {
request.head(uri, function (err, res, body) {
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
但当我在for循环中运行此代码时,保存的图像已损坏。更重要的是,并非所有像素都被下载。仅保存部分图像
有办法解决这个问题吗?嗯,我找到了解决问题的办法。原因是在映像完全写入磁盘之前,另一个线程会启动,以此类推。 为了解决这个问题,我使用Q-IO库实现了承诺
var Apps = require("q-io/http");
var qfs = require("q-io/fs");
var download = function(uri, filename, callback){
Apps.read(uri).then(function(data){
callback(data);
}, function(err){
console.log('err: ' + err);
});
};
download('https://www.google.com/images/srpr/logo3w.png', 'test.jpg', function(data){
console.log('done');
qfs.write("test.jpg", data);
});
但我没有使用for循环,而是使用了自调用函数