I'm trying to execute a node script that downloads some urls. It looks like this:
const https = require('https');
const fs = require('fs');
const async = require('async');
function download_cb(err) {
if (err) {
console.log("Download error:"+err);
}
}
function download_file(task) {
const url = task.url;
const dest = task.dest;
var file = fs.createWriteStream(dest);
var request = https.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(download_cb); // close() is async, call cb after close completes.
});
}).on('error', function(err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
download_cb(err.message);
});
};
function get_urls() {
var queue = async.queue(download_file, 10);
const urls = []; // some array of urls
for (var i=0; i<urls.length; i++) {
queue.push({url: urls[i], dest: dest/*whatever*/});
}
return queue.drain();
}
(async () {
await get_urls().then(()=>{
console.log("All done");
})
})();
This ends up downloading only the first 10 urls and then exits, while the "All done" message is never shown. It somehow seems that the promise returned by the function (queue.drain()) is never resolved even though it's being awaited for. What am I missing?
I also tried:
queue.drain = function() {
console.log("All files are downloaded");
};
inside the get_urls function but it doesn't change anything and the code in it isn't get executed either.