Today, I'm try to download many file from my server
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
}
when I run code:
node download.js
System downloaded all photos, but size of photo is 0kb. and has error:
stream.js:81 throw er; // Unhandled stream error in pipe. ^ Error: OK, close
Beside, when I Throw Loop (EX: fix dataJson.Person[i].Username, change i to 10)
after running code, system reurn correct photo.
what are happening? How to fix it?
best regard.!