Delete several files in node.js

后端 未结 8 1412
自闭症患者
自闭症患者 2021-02-15 23:58

What is the best way to delete several files in node.js?

function deleteFiles(files, callback){
    ...
}

var files = [\'file1.js\', \'file2.jpg\', \'file3.css\         


        
8条回答
  •  广开言路
    2021-02-16 00:13

    Promisified and slightly improved version Chris answer.

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

提交回复
热议问题