Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete several files in node.js

Tags:

node.js

What is the best way to delete several files in node.js?

function deleteFiles(files, callback){
    ...
}

var files = ['file1.js', 'file2.jpg', 'file3.css'];
deleteFiles(files, callback);
like image 766
gang Avatar asked Jan 12 '13 17:01

gang


People also ask

How do I delete multiple files in node JS?

To delete a file in Node. js, we can use the unlink() function offered by the Node built-in fs module. The method doesn't block the Node. js event loop because it works asynchronously.

How do I delete multiple files in a folder?

Delete key You can delete multiple files or folders by holding down Ctrl and clicking each file or folder before pressing Delete . You can hold down Shift while pressing Delete to prevent files from going to the Recycle Bin when deleted.


1 Answers

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

like image 172
Chris Avatar answered Sep 28 '22 12:09

Chris