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

时间:2022-07-18 13:21:55

I want to delete 3 files in list_file_to_delete but 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

我想在list_file_to_delete中删除3个文件,但我不知道在这里放到“三个文件的路径”的路径是什么?我是否需要循环/ for / forEach函数来删除所有或只需要一个包含3条路径的字符串var string =“... a1.jpg,... a2.jpg,... a3.jpg”?提前致谢

in delete.js file

在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 myapp directory

这是myapp目录

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

1 个解决方案

#1


16  

fs.unlink takes 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()));

#1


16  

fs.unlink takes 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()));