T
T
teodor7teodor72019-01-06 12:35:10
Node.js
teodor7teodor7, 2019-01-06 12:35:10

How to properly wait for files to load on nodejs?

It is necessary to upload all files, and then send a message that all files have been uploaded.

function getFiles(arrContent, folder) {
  arrContent.forEach((content, i, arr) => {
    const file = fs.createWriteStream(`${inputFolder}/${folder}/${i}.jpg`);
    const request = http.get(`${getUrl}${encodeURI(content.replace(/\s+/g,' ').trim())}`, (response) => {
      response.pipe(file);
      file.on('finish', () => {
        file.close(); // close() is async, call cb after close completes.
              }).on('error', (err) => { // Handle errors
        fs.unlink(`${inputFolder}/${entities.encode(folder)}/${i}.jpg`);
        console.log(`Error ${inputFolder}/${entities.encode(folder)}/${i}.jpg - not found!`);
      });
    });
  });
}

It turns out that the function sends requests and continues the execution of the code. I need to wait until all files are fully loaded, and then run a message that all files in the array are saved.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SagePtr, 2019-01-06
@SagePtr

Wrap the processing of each file in a promise, and process them through Promise.all, as an option

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question