Delete several files in node.js

后端 未结 8 1406
自闭症患者
自闭症患者 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:06

    You can use this to delete multiple files (for linux env ES6 syntax)

    import {execSync} from "child_process";
    ...
    
    ...
    const files = ['file1.js', 'file2.jpg', 'file3.css'];
    // just example path
    const rootDir = '/var/www/files/';
    if (files.length > 0)
        execSync('rm -f' + files.map(o => rootDir + o.replace(/(\s+)/g, '\\$1')).join(' '));
    

    rm -f to ignore if files are missing and replace to escape spaces if file names contains it,

    0 讨论(0)
  • 2021-02-16 00:06

    Best way is delete files synchronously into a loop using unlinkSync(path) function (see the doc), from node v7.6.0 so far.

    Syntax is provided below:

    // myListOfFiles will be your list of files with paths relative to your script.
    myListOfFiles.forEach(filePath => {
     fs.unlinkSync(filePath);
     return;
    });
    

    A reference here

    0 讨论(0)
  • 2021-02-16 00:12

    I personally like shortcode (in one line)

    files.forEach(path => fs.existsSync(path) && fs.unlinkSync(path))
    

    So maybe using async/await style it's easier (complete example):

    try {
      var files = ['file1.js', 'file2.jpg', 'file3.css'];
      files.forEach(path => fs.existsSync(path) && fs.unlinkSync(path))
      // success code here
    } catch (err) {
      // error handling here
      console.error(err)
    }
    
    0 讨论(0)
  • 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();
                    }
                });
            });
        })
    }
    
    0 讨论(0)
  • 2021-02-16 00:18

    This deletes the files in an array and runs the callback once only after all files have been deleted.

    function deleteFiles(files, callback){
       if (files.length==0) callback();
       else {
          var f = files.pop();
          fs.unlink(f, function(err){
             if (err) callback(err);
             else {
                console.log(f + ' deleted.');
                deleteFiles(files, callback);
             }
          });
       }
    }
    
    0 讨论(0)
  • 2021-02-16 00:20

    Here is a code to delete several files from directory in node.js,

    var fs = require('fs');
    
    var removeFile= function (err) {
        if (err) {
            console.log("unlink failed", err);
        } else {
            console.log("file deleted");
        }
    }
    
    fs.unlink('filepath', removeFile); // for single file
    
    
    //for multiple files...
    
    _.map(yourArray,(files)=>{
        fs.unlink('filepath', removeFile);
    });
    
    0 讨论(0)
提交回复
热议问题