Skip to content

Instantly share code, notes, and snippets.

@kaizhu256
Last active December 10, 2015 23:48
Show Gist options
  • Save kaizhu256/4511667 to your computer and use it in GitHub Desktop.
Save kaizhu256/4511667 to your computer and use it in GitHub Desktop.
nodejs - asynchronously, recursively delete directories and files in under 100 lines of code
/*jslint bitwise: true, indent: 2, nomen: true, regexp: true, stupid: true*/
(function () {
'use strict';
exports.requireFs = require('fs');
function FsRemoveR() {
}
FsRemoveR.prototype.callbackDefault = function (err) {
if (err) {
console.error(err.stack);
}
};
FsRemoveR.prototype.io = function (filename, parent, action) {
var self = this;
exports.requireFs[action](filename, function (err, arr) {
self.recurse(filename, parent, action, err, arr);
});
};
FsRemoveR.prototype.recurse = function (filename, parent, action, err, arr) {
var ii, kk, tmp;
switch (action) {
case 'readdir':
if (err) {
this.callback(err);
return;
}
if (arr.length) {
tmp = parent;
parent = {};
parent[filename] = tmp;
for (ii = 0; ii < arr.length; ii += 1) {
tmp = filename + '/' + arr[ii];
parent[tmp] = {};
this.io(tmp, parent, 'unlink');
}
} else {
this.io(filename, parent, 'rmdir');
}
return;
case 'removeParent':
if (!parent) {
this.callback();
return;
}
delete parent[filename];
for (kk in parent) {
if (parent.hasOwnProperty(kk)) {
if (tmp) {
return;
}
tmp = true;
}
}
this.io(kk, parent[kk], 'rmdir');
return;
case 'rmdir':
if (err) {
this.callback(err);
return;
}
this.recurse(filename, parent, 'removeParent');
return;
case 'unlink':
if (err) {
this.io(filename, parent, 'readdir');
return;
}
this.recurse(filename, parent, 'removeParent');
return;
}
};
FsRemoveR.prototype.remove = function (filename, callback) {
this.callback = callback || this.callbackDefault;
this.io(filename, null, 'unlink');
};
exports.fsRemoveR = function (filename, callback) {
new FsRemoveR().remove(filename, callback);
};
//// test
exports.requireFs.mkdirSync('/tmp/foo');
exports.requireFs.mkdirSync('/tmp/foo/bar');
exports.requireFs.writeFileSync('/tmp/foo/aa', 'hello');
exports.requireFs.writeFileSync('/tmp/foo/bb', 'bye');
exports.fsRemoveR('/tmp/foo', function (err) {
if (err) {
console.error(err.stack);
return;
}
console.log('finished asynchronously recursively deleting /tmp/foo');
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment