Skip to content

How to capture response-end event in node.js express

My case: I have to make an api to download some images, zip them, and send back to client:

  • Client call api to request a zip file of images
  • API download images and store them in Temp folder
  • Zip the folder and send back to client
  • Delete the temp folder

So, how to know: when does the “Sending response” end? (client received the zip file)

Just need to use:

res.on('finish', function () {
      console.log('Finished sending coverage data.');
 });

My code:

router.post('/', async (req, res, next) => {
  const {url, number} = req.body;
  try {
    const folderName = await downloader.download(url, number);
    const folderPath =  __basedir + '/storage/temp/' + folderName;
    const archive = archiver('zip', { zlib: { level: 9 }});
    archive.directory(folderPath, false);
    res.set({
      'Content-Type': 'application/zip',
      'Content-Disposition': 'attachment; filename="' + folderName + '.zip' + '"'
    });
    res.on('finish', function () {
      console.log('Finished sending coverage data.');
      rimraf(folderPath, () => {});
    });
    archive.pipe(res);
    archive.finalize();
  } catch (e) {
    console.log(e.message);
    res.sendStatus(500) && next(e);
  }
});

Happy coding!!

Published inUncategorized

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *