Delete several files in node.js

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

    Asynchronous:

    var fs = require('fs');
    
    function deleteFiles(files, callback){
      var i = files.length;
      files.forEach(function(filepath){
        fs.unlink(filepath, function(err) {
          i--;
          if (err) {
            callback(err);
            return;
          } else if (i <= 0) {
            callback(null);
          }
        });
      });
    }
    
    var files = ['file1.js', 'file2.jpg', 'file3.css'];
    
    deleteFiles(files, function(err) {
      if (err) {
        console.log(err);
      } else {
        console.log('all files removed');
      }
    });
    

    http://nodejs.org/docs/v0.4.1/api/fs.html#file_System

提交回复
热议问题