ItsGreg ItsGreg - 2 months ago 12
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

, 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:'/upload', fileUpload.single('asset'), (req, res) => {
// Do something with the file
setTimeout(() => {
// Delete the file
}, 600000);


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 = {};'/upload', fileUpload.single('asset'), (req, res) => {
  // Do something with the file
  pending[file_name] = (new Date()).getTime();

     // check each element of pending and see if it needs to be deleted
}, 30000);