如何异步删除多个文件?

时间:2015-05-23 21:06:34

标签: javascript node.js asynchronous fs

假设我有一个包含多个文件路径的数组。我想异步删除这些文件。

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

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

我遇到了这个解决方案Delete several files in node.js,但我认为它违反了node.js的做法(for循环中的异步函数)。还有其他更好的解决方案吗?

3 个答案:

答案 0 :(得分:1)

尝试递归选项(问题中链接的代码):

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

答案 1 :(得分:1)

如果要以异步方式运行任意任务列表(取消链接文件),但知道它们何时完成,则可以使用async.js模块。它可以串行运行任务parallel

所以将所有unlink函数调用推送到一个数组中,然后调用async.parallel()让它们飞起来。然后,当它们全部完成后,您将进入单一可管理回调。

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" );          
});

答案 2 :(得分:0)

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();
                }
            });
        });
    })
}