Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all sub directories with rimraf on node.js

Tags:

node.js

I have a directory structure where certain folder Data has sub directories. At some point I want those removed all at once and I've installed the otherwise awesome rimraf package for node.js

My code so far:

var dataPath === Path.normalize(__dirname + '/backend/data/');

rimraf(dataPath, function(error) {
    console.log('Error: ', error);
});

I've tried with both /backend/data/ and /backend/data/ *, but none seems to do the trick - the first deletes the entire data folder and the second fires an error 'Can't delete null'

I guess I could scan the main directory, find all sub folders and delete them one by one, but if this can be done with rimraf or a similar package, I'd rather go with it.

like image 912
Nat Naydenova Avatar asked Feb 27 '15 17:02

Nat Naydenova


2 Answers

The easiest solution is to just re-create the data directory after rimraf finishes deleting it. Depending on your use case, that can introduce a race condition, but I doubt rimraf itself is race-safe in any situations where that isn't.

Another option is to read the contents of the directory and rimraf each of those, but that is more work and doesn't avoid any race conditions that would affect the first option.

like image 155
Trott Avatar answered Oct 11 '22 21:10

Trott


The current version of rimraf supports globs, so one could just add an asterisk to the end of the folder, like so:

rimraf( path.join(__dirname, "./uploads/*"), (err) => { ... });

like image 32
bchr02 Avatar answered Oct 11 '22 22:10

bchr02