ItsGreg ItsGreg - 1 month ago 7
Javascript Question

Will using setTimeout ensure something executes in NodeJS?

I'm creating a REST backend using ExpressJS. A part of the backend allows users to upload file assets, which should only exist for 10 minutes.

It safe to use

setTimeout
, to delete the file after 10 minutes, or are there better ways of doing this in NodeJS? How can I ensure the file is deleted? Here is my current solution:

router.post('/upload', fileUpload.single('asset'), (req, res) => {
// Do something with the file
res.status(201).end();
setTimeout(() => {
// Delete the file
}, 600000);
});

Answer

Your approach is not going to scale, as it will potentially create a huge number of delayed methods. Better way is to store the information about the file into some associative array (object) such as :

{ "path":"date_uploaded" }

And to check every, say, XX seconds if there is anything that needs deleting with setInterval(). I.e. go through the whole structure and see if anythign was created more then 10 minutes ago. For all such elements you delete the file and remove it from the array.

var pending = {};

router.post('/upload', fileUpload.single('asset'), (req, res) => {
  // Do something with the file
  pending[file_name] = (new Date()).getTime();
  res.status(201).end();
});

setInterval(
function(){
     // check each element of pending and see if it needs to be deleted
}, 30000);
Comments