Home > database >  Synchronous download in loop
Synchronous download in loop

Time:10-26

Need to query downloading of file array

I have an array with URL's of files to dowload:

const arrUrl = [
   'http://server.domain/path/file1.jpg',
   'http://server.domain/path/file2.jpg',
   'http://server.domain/path/file3.jpg', 
];

when i try to download files with Axios and code:

arrUrl.forEach(async (element: string, i:number) => {
     const response = await new Axios({responseType: 'stream'}).get(element);
     await writeFile('./files/' i, response.data);
     console.log(element);
});

All files start downloading at one time. But how can i download files in query mode? one-by-one

CodePudding user response:

This can be achieved using async function with for-in (index) of for-of (element) loop. Since we need to deal with loop index for-in is suitable here.

const arrUrl = [
    'http://server.domain/path/file1.jpg',
    'http://server.domain/path/file2.jpg',
    'http://server.domain/path/file3.jpg',
];

async function downloadFiles(arrUrl) {
    for (let index in arrUrl) {
        const element = arrUrl[index];
        const response = await new Axios({ responseType: 'stream' }).get(element);
        await writeFile('./files/'   index, response.data);
    }
}

downloadFiles(arrUrl);

CodePudding user response:

You can use for await:

for await (const url of arrUrl) {
    const response = await new Axios({ responseType: 'stream'}).get(url);
    await writeFile(`./files/${url}`, response.data);
}

This will iterate over the URLs and send the next HTTP request once the previous one finished. Don't forget to handle HTTP errors though!

  • Related