Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

96
Vistas
How to wait till a task runs to completion in Node JS

I have an array of image urls. Once I download all the images successfully, post completion, I want to write output to a separate file in Node/Express.

funtion extractImages(elems) {

Array.from(elems).filter((url) => {
            console.log("url tried", url);
            var _name = url.split('/').pop(-1).toLowerCase().replace("%20", "-");
            console.log("_name tried", _name);
            var file = fs.createWriteStream(_name);
            https.get(url, function(response) {
                console.log("*******downloaded********");
                response.pipe(file);
                file.on("finish", () => {
                    file.close();
                    console.log("Download Completed, set image now *****", `url(${_name})`);
                });
            });
    })
}
router.post('/api/stuff', async (req, res, next) => {
    // .....
    // .....
    var arr = ['...','...'];
    extractImages(arr);
    // only do it post images are downloaded
            filename = uuid();
        fs.writeFile(`${filename}.html`, dom.serialize(), function (err) {
            if (err) throw err;               
            console.log('Results Received, file writen');
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify({ done: "test" }));
        }); 

But because images downloading takes some time, fs.writeFile runs before. I could wait by setTimeout and passing a delay, but in this scenario what's a better approach to handle the same?

UPDATE

If I put the writeFile inside file.on("finish", callback that runs multiple times for all elements in the array. I want to run and write the file only once.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda