file path and delete file in nodejs

user3044147 picture user3044147 · Nov 28, 2013 · Viewed 38k times · Source

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

in delete.js file

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
      /app
          /js
             delete.js
      /public
             /images
                    a1.jpg
                    a2.jpg
                    a3.jpg
      server.js

Answer

Mike 'Pomax' Kamermans picture Mike 'Pomax' Kamermans · Nov 28, 2013

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

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

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

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