Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file path and delete file in nodejs

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
like image 413
user3044147 Avatar asked Nov 28 '13 02:11

user3044147


People also ask

How do you delete a file in node JS?

js fs-extra remove() Function. the remove() function deletes the given file or directory. All the files inside a directory are deleted.

How do I delete a file path?

Open My Computer or Windows Explorer. We recommend you make sure the directory or folder is empty before proceeding, unless you intend to delete everything in it. Locate the file or folder you want to delete and right-click it. Choose the Delete option from the pop-up menu.

Which method is used to delete a file in node JS?

rm() Method. The fs. rm() method is used to delete a file at the given path.

How do I delete a .js file?

js, you can use the fs. unlink() method provided by the built-in fs module to delete a file from the local file system. Here is an example that demonstrates how you can use this method: const fs = require('fs') // delete a file fs.


1 Answers

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()));
like image 77
Mike 'Pomax' Kamermans Avatar answered Sep 22 '22 22:09

Mike 'Pomax' Kamermans