Skip to content

Commit

Permalink
feat: add a mkDirSync method that recursively creates unexisting path…
Browse files Browse the repository at this point in the history
… directories
  • Loading branch information
teclone committed Jul 20, 2018
1 parent ba2ec9d commit 8060dd0
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/modules/Util.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import fs from 'fs';
import path from 'path';

/**
* Utility module
* this module defines a bunch of utility functions that will be relevant to most other modules
Expand Down Expand Up @@ -92,7 +95,7 @@ export default {
if (!this.isCallable(callback)) {
throw new TypeError('argument one is not a function');
}
scope = this.isObject(scope) ? scope : this;
scope = this.isObject(scope) ? scope : null;
parameters = this.makeArray(parameters);

return (...args) => {
Expand Down Expand Up @@ -198,5 +201,34 @@ export default {
dest = run.call(this, dest, object);
}
return dest;
},

/**
* creates a directory recursively and synchronously
*@param {string} dir - the directory to create
*@returns {boolean}
*/
mkDirSync(dir) {
if (typeof dir !== 'string')
throw new TypeError('argument one is not a string');
if (dir === '/' || dir === '' || fs.existsSync(dir))
return false;

//search backwards
dir = dir.replace(/\/+$/, '');
let existingPath = '',
testPath = dir;
while (existingPath === '' && testPath !== '/') {
testPath = path.join(testPath, '../');
if (fs.existsSync(testPath))
existingPath = testPath;
}

let pathTokens = dir.split(existingPath)[1].split('/');
for (let pathToken of pathTokens) {
existingPath = path.join(existingPath, '/', pathToken);
fs.mkdirSync(existingPath);
}
return true;
}
};

0 comments on commit 8060dd0

Please sign in to comment.