Skip to content

Instantly share code, notes, and snippets.

@nebhale
Created November 21, 2012 08:31
Show Gist options
  • Save nebhale/4123809 to your computer and use it in GitHub Desktop.
Save nebhale/4123809 to your computer and use it in GitHub Desktop.
Node-friendly `mkdir -p` and `rm -r`
/*jshint node:true*/
'use strict';
var fs = require('fs');
var path = require('path');
/**
* Callback function for the `fs.exists()` function. If the directory exists, calls the completion callback
*
* @param {string} directory The directory to make
* @param {string} permissions The permissions of the created directory
* @param {function} callback No arguments are given to the completion callback
* @param {boolean} exists Whether the director exists
*/
function _mkdir(directory, permissions, callback, exists) {
if (exists) {
callback();
} else {
var parent = path.dirname(directory);
var newCallback = fs.mkdir.bind(null, directory, permissions, callback);
fs.exists(parent, _mkdir.bind(null, parent, permissions, newCallback));
}
}
/**
* Creates a new directory, building any needed parent directories
*
* @param {string} directory The directory path to create. Relative paths are resolved relative to the current working directory.
* @param {string} permissions The file permissions of the created directory. Permissions default to '0777'.
* @param {function} callback No arguments other than a possible exception are given to the completion callback
*/
function mkdir(directory, permissions, callback) {
fs.exists(directory, _mkdir.bind(null, directory, permissions, callback));
}
module.exports = mkdir;
/*jshint node:true*/
'use strict';
require('../../../source/server/util/handle');
var fs = require('fs');
var path = require('path');
var when = require('when');
var _ = require('underscore');
function _rm(candidate) {
var deferred = when.defer();
fs.stat(candidate, function(stat) {
if (stat.isDirectory()) {
fs.readdir(candidate, function(files) {
var children = _.map(files, function(file) {
return _rm(path.join(candidate, file));
});
when.all(children, function() {
fs.rmdir(candidate, deferred.resolve.handle(deferred));
}, function(err) {
deferred.reject(err);
});
}.handle(deferred));
} else {
fs.unlink(candidate, deferred.resolve.handle(deferred));
}
}.handle(deferred));
return deferred;
}
function rmdir(directory, callback) {
when(_rm(directory), function() {
callback();
}, function(err) {
callback(err);
});
}
module.exports = rmdir;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment