Engineering Machine
Engineering Machine

Reputation: 642

How can I delete multiple files asynchronously?

Assume I have an array with paths to multiple files. I would like to delete these files asynchronously.

var files = ['file1.txt', 'file2.txt'];

fs.unlink(..., callback())

I came across with this solution Delete several files in node.js but I think it violates node.js practices (asynchronous function inside a for loop). Is there any other, better solution for this?

Upvotes: 2

Views: 3414

Answers (3)

Pradeep Nooney
Pradeep Nooney

Reputation: 820

async deleteAll(filePathsList) {
  try {
    await this.deleteFiles(filePathsList);
    logger.log('info', "Following files deleted successfully from EFS --> " + filePathsList.toString());
    return true;
  } catch (error) {
    logger.log('error', error.stack || error);
    logger.log('error', "Error occured while deleting files from EFS");
    return false;
  }
}
async deleteFiles(files) {
  return new Promise((resolve, reject) => {
    let i = files.length;
    files.forEach(function(filepath) {
      fs.unlink(filepath, function(err) {
        i--;
        if (err && err.code == 'ENOENT') {
          // file doens't exist
          logger.log('info', "Following file doesn't exist, So won't be deleted-->" + (filepath || ''));
        } else if (err) {
          // other errors, e.g. maybe we don't have enough permission
          logger.log('error', "Error occured while deleting the file  " + (filepath || '') + " due to error" + err);
          reject(err);
          return;
        } else if (i <= 0) {
          resolve();
        }
      });
    });
  })
}

Upvotes: 0

Aaron
Aaron

Reputation: 459

If you want to run a an arbitrary list of tasks (unlinking files) asynchronously, but know when they are all done, you can use the async.js module. It can run tasks in series and parallel.

So push all your unlink function calls into an array, then call async.parallel() and let them fly. Then when they are all done, you land in a single manageble callback.

var files = ['file1.txt', 'file2.txt'];
var myParallelTasks = [];
files.forEach( function( fileName )
{
    myParallelTasks.push( fs.unlink( fileName, function(callback)
    {
       callback();
    })
    );
}

async.parallel( myParallelTasks, function()
{
    // all done
    console.log( "all done" );          
});

Upvotes: 2

zmii
zmii

Reputation: 4277

Try the option of recursion (code from your link in the question):

function deleteFiles(files, callback){
  var i = files.length;
  var file = files.pop();
  if ( file == undefined ) {
    callback();
  } else {
    // do the unlinking ...
    deleteFiles(files, callback);
  }
}

Upvotes: 1

Related Questions