nodejs中的文件路径和删除文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20256901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:23:03  来源:igfitidea点击:

file path and delete file in nodejs

node.jsfile-ioexpresspathfilepath

提问by user3044147

I want to delete 3 files in list_file_to_deletebut I do not know what is the path to put to "path to three files here"?. Do I need for loop/for in/forEach function to delete all or just need a string with 3 paths likely var string = "...a1.jpg, ...a2.jpg,...a3.jpg"? Thanks in advance

我想删除其中的 3 个文件,list_file_to_delete但我不知道“此处的三个文件的路径”的路径是什么?。我是否需要 for loop/for in/forEach 函数来删除全部或只需要一个可能有 3 个路径的字符串var string = "...a1.jpg, ...a2.jpg,...a3.jpg"?提前致谢

in delete.jsfile

delete.js文件中

var list_file_to_delete = ["/images/a1.jpg", "/images/a2.jpg", "/images/a3.jpg"]
fs.unlink(path to three files here, function(err) {console.log("success")})

this is myappdirectory

这是myapp目录

 myapp
      /app
          /js
             delete.js
      /public
             /images
                    a1.jpg
                    a2.jpg
                    a3.jpg
      server.js

回答by Mike 'Pomax' Kamermans

fs.unlinktakes a single file, so unlink each element:

fs.unlink采用单个文件,因此取消链接每个元素:

list_of_files.forEach(function(filename) {
  fs.unlink(filename);
});

or, if you need sequential, but asynchronous deletes you can use the following ES5 code:

或者,如果您需要顺序但异步的删除,您可以使用以下 ES5 代码:

(function next(err, list) {
  if (err) {
    return console.error("error in next()", err);
  }
  if (list.length === 0) {
    return;
  }
  var filename = list.splice(0,1)[0];
  fs.unlink(filename, function(err, result) {
    next(err, list);
  });
}(null, list_of_files.slice()));