Reputation: 6929
I am looking for a way to empty a directory in Express.
Basically, I have a tmp
directory where I am storing temporary files and every so often I just want to empty the folder of all files, but not delete the folder itself.
What is the best way to do this? I am currently using Node v0.8.9
and Express v.3.0.0rc4
.
Upvotes: 0
Views: 133
Reputation: 732
I wrote this function called remove folder. It will recursively remove all the files and folders in a location. The only package it requires is async. var async = require('async');
function removeFolder(location, removeFolder, next) {
fs.readdir(location, function (err, files) {
async.each(files, function (file, cb) {
file = location + '/' + file
fs.stat(file, function (err, stat) {
if (err) {
return cb(err);
}
if (stat.isDirectory()) {
removeFolder(file, true, cb);
} else {
fs.unlink(file, function (err) {
if (err) {
return cb(err);
}
return cb();
})
}
})
}, function (err) {
if (err) return next(err)
fs.rmdir(location, function (err) {
return next(err)
})
})
})
}
I changed it a little to not remove the original folder call it using:
removeFolder('/tmp', false, function(err){
//callback
})
Upvotes: 0
Reputation: 5157
Either check this little but sweet module.
https://github.com/isaacs/rimraf
Or check the official docs and examples.
http://nodejs.org/docs/v0.4.1/api/fs.html#file_System
Upvotes: 2