Ensure directory exists is now recursive

pull/2/head
Louis Chatriot 12 years ago
parent 72efd8fc0f
commit e2b73d9e6f
  1. 27
      lib/customUtils.js

@ -1,20 +1,35 @@
var fs = require('fs') var fs = require('fs')
, crypto = require('crypto') , crypto = require('crypto')
, path = require('path')
; ;
/** /**
* Check if directory exists and create it on the fly if it is not the case * Check if a directory exists and create it on the fly if it is not the case
* TODO: make recursive * Does it recursively
* cb is optional, signature: err
*/ */
function ensureDirectoryExists (dir, cb) { function ensureDirectoryExists (dir, cb) {
var callback = cb || function () {}; var callback = cb || function () {}
, parts, currentPart
;
if (typeof dir === 'string') { return ensureDirectoryExists({ toTreat: dir, treated: '' }); }
if (dir.toTreat.length === 0) { return callback(); }
parts = dir.toTreat.split(path.sep);
currentPart = path.join(dir.treated, parts[0]);
fs.exists(dir, function (exists) { parts = parts.slice(1).join(path.sep);
fs.exists(currentPart, function (exists) {
if (exists) { if (exists) {
return callback(); return ensureDirectoryExists({ toTreat: parts, treated: currentPart }, callback);
} else { } else {
fs.mkdir(dir, '0777', callback); return fs.mkdir(currentPart, '0777', function (err) {
if (err) { return callback(err); }
return ensureDirectoryExists({ toTreat: parts, treated: currentPart }, callback);
});
} }
}); });
} }

Loading…
Cancel
Save