January 23, 2013

Recursive remove directory for Node.js

It turned out that Node.js fs module does not have a method to remove the directory and its content recursively. Instead you should go through the directory structure and remove atomic items, i.e. individual files and empty directories. So I found a nice gist by Takuo Kihira at https://gist.github.com/2367067 made in JavaScript and decided to make a CoffeeScript version of it:

But in real life you should better use the system command:

child_process.exec "rm -rf #{directory}"

This might be much faster at the cost of platform dependency.

2 comments:

Audio Collapse said...

а так?

1) прочитать директорию
2) удалить файлы в ней
3) удалить родительскую директорию

function rmdir(dir){
fs.readdir(dir, function(err, files){
c = files.length;
for(i=с;i=0;--i){ fs.unlink(dir + '/' + files[i]) };
});
fs.rmdir(home_dir, function(){
console.log(home_dir + ' was removed!');
});
}

4) можно добавить еще проверку на вложенные директории

Anonymous said...

Wikindly | Trending Female Celebrities Biographies