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.