I'm looping through a number of image uri's to download them locally.
This is the code I'm using:
const optionsImg = {
url: basePath,
headers: {
'User-Agent': 'request'
}
};
let download = function(url, filename, callback) {
optionsImg.url = url
request.head(optionsImg, (err, res, body) => {
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(optionsImg).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
But it's only ever saving the last image in the list. What I suspect is happening is it's trying to download async, and the fs.createWriteStream keeps being interrupted, till the list has finished. Therefore only downloading the last image successfully.
The console.logs do show different content-length.
How best to get round this issue? Thanks in advance.
Edit: This is the loop code:
for (let x = 0; x < pics.length; x++) {
download(pics[x], localPath + x + '.jpeg', function() {
console.log('done');
});
}