I am trying to download pdf files from a URL and save them to my local disk. The issue is that I need each file downloaded one at a time with a time delay in between (the delay should be about 1 second). That is to say: after one file is downloaded, the script should wait a full second before downloading the next file).
- Wait for the file to be downloaded
- Wait for the file to be saved to disk
- Wait a full second
- Start that loop over again
The Code:
const fs = require('fs');
const fetch = require('node-fetch');
const arrayOfURL = ['www.link.com/file1', 'www.link.com/file2', 'www.link.com/file3'];
const wait = waitTime => new Promise(resolve => setTimeout(resolve, waitTime));
(async() => {
async function downloadAllFiles() {
return new Promise((resolve, reject) => {
(async() => {
for (let i = 0; i < arrayOfURL.length; i++) {
console.log(`File ${i} Download Begun`);
const response = await fetch(arrayOfURL[i]);
const writeStream = fs.createWriteStream(i + '.pdf');
response.body.pipe(writeStream);
async function write() {
return new Promise((resolve, reject) => {
writeStream.on('finish', function () {
resolve('complete');
});
});
}
await write();
console.log(`----- DOWNLOAD COMPLETE -----`);
await wait(1000 * i);
if (i === 2) {
resolve('complete');
}
}
})();
});
}
await downloadAllFiles();
})();
What I want the logs is to show this:
console.log(`File 0 Download Begun`);
console.log(`File Saved Locally`);
console.log(`----- DOWNLOAD COMPLETE -----`);
***Wait 1 second***
console.log(`File 1 Download Begun`);
console.log(`File Saved Locally`);
console.log(`----- DOWNLOAD COMPLETE -----`);
***Wait 1 second***
console.log(`File 2 Download Begun`);
console.log(`File Saved Locally`);
console.log(`----- DOWNLOAD COMPLETE -----`);
***Wait 1 second***
Instead the logs show this:
console.log(`File 0 Download Begun`);
console.log(`File 1 Download Begun`);
console.log(`File 2 Download Begun`);
console.log(`File Saved Locally`);
console.log(`----- DOWNLOAD COMPLETE -----`);
console.log(`File Saved Locally`);
console.log(`----- DOWNLOAD COMPLETE -----`);
console.log(`File Saved Locally`);
console.log(`----- DOWNLOAD COMPLETE -----`);
***Downloaded at the same time***
And the delay is also not working (all files are downloaded at once) as i
in await wait(1000 * i)
is always 0;
Any help is appreciated.