alo*_*uan 2 javascript download node.js
今天,我尝试从我的服务器下载许多文件
download.js
function getPhotos(req, res) {
//Get User Photos
var fileReader = fs.readFile('./../data/user.json', 'utf8', function(err, data) {
if (err)
console.log(err);
else {
var dataJson = JSON.parse(data);
//console.log(dataJson.Person);
for (var i = 0; i < dataJson.Person.length; i++) {
var options = {
host : '10.16.47.128', // Local Server IPAddress
port : 2013, //Port
path : '/ExternalServer/avatar/' + dataJson.Person[i].Username + '.jpg',
};
//console.log(dataJson.Person[i].Username);
var fileAvatarPhotos = fs.createWriteStream('./../avatar/' + dataJson.Person[i].Username + '.jpg');
fs.exists(fileAvatarPhotos, function(exists) {//Check Exist File
if (exists) {
var req = http.get(options, function(res) {
//console.log(res);
res.pipe(fileAvatarPhotos);
});
} else {
var req = http.get(options, function(res) {
fs.writeFile(fileAvatarPhotos, '', function(err) {
if (err)
return console.log(err);
var req = http.get(options, function(res) {
//console.log(res);
res.pipe(fileAvatarPhotos);
});
});
});
}
});
}
}
});
//End Get User Photos
}
Run Code Online (Sandbox Code Playgroud)
当我运行代码时:
node download.js
Run Code Online (Sandbox Code Playgroud)
系统下载了所有照片,但照片大小为0kb.并有错误:
stream.js:81 throw er; //管道中未处理的流错误.^错误:好的,关闭
旁边,当我投掷循环(EX:修复dataJson.Person [i] .Username,将i更改为10)
运行代码后,系统重新生成正确的照片.
发生了什么事?怎么解决?
最良好的问候.!
在for循环中实现这样的功能并不是一个好主意.那是因为在循环内部你有异步操作,但是循环的每次迭代都会立即执行.在您的情况下,您正在定义fileAvatarPhotos,它是一个WriteStream对象.该http.get方法是异步的,所以在其回调你可以使用fileAvatarPhotos用于循环的第三次迭代,或第四或也许第一个定义.这取决于.您可以尝试将代码转换为以下内容:
var files = ["file1.jpg", "file2.jpg", "file3.jpg"];
var readFile = function(callback) {
if(files.length > 0) {
var file = files.shift();
http.get({path: file}, function(res) {
// ... process the result
readFile(callback);
})
} else {
callback();
}
}
readFile(function() {
console.log("reading finishes");
});
Run Code Online (Sandbox Code Playgroud)
即readFile一次又一次地被调用,直到文件数组中没有更多元素.
| 归档时间: |
|
| 查看次数: |
2251 次 |
| 最近记录: |