Skip to content

Instantly share code, notes, and snippets.

@wilensky
Last active June 16, 2019 20:05
Show Gist options
  • Save wilensky/30780b42cc1978aed378 to your computer and use it in GitHub Desktop.
Save wilensky/30780b42cc1978aed378 to your computer and use it in GitHub Desktop.
Recursive directory creation using `fs.mkdirSync()`. Recreates directory tree in series.
var fs = require('fs');
/**
* Splits whole path into segments and checks each segment for existence and recreates directory tree from the bottom.
* If since some segment tree doesn't exist it will be created in series.
* Existing directories will be skipped.
* @param {String} directory
*/
function mkdirSyncRecursive(directory) {
var path = directory.replace(/\/$/, '').split('/');
for (var i = 1; i <= path.length; i++) {
var segment = path.slice(0, i).join('/');
!fs.existsSync(segment) ? fs.mkdirSync(segment) : null ;
}
}
@ooip
Copy link

ooip commented Jun 10, 2018

Quick fix for absolute paths:

function mkdirSyncRecursive(directory) {
    var path = directory.replace(/\/$/, '').split('/');
    for (var i = 1; i <= path.length; i++) {
        var segment = path.slice(0, i).join('/');
        segment.length > 0 && !fs.existsSync(segment) ? fs.mkdirSync(segment) : null ;
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment