Created
March 2, 2019 17:55
-
-
Save kapraran/52949ffe13bd6dc6979ee56f2d08ceac to your computer and use it in GitHub Desktop.
A quick way to create a new directory and every necessary subdirectory. For a better tested solution, use 'mkdirp' package.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path') | |
const fs = require('fs') | |
const util = require('util') | |
const fsMkdir = util.promisify(fs.mkdir) | |
const fsExists = util.promisify(fs.exists) | |
/** | |
* | |
* @param {string} dirpath | |
*/ | |
const mkdirp = function(dirpath) { | |
const segments = path.posix.resolve(dirpath).split('/') | |
let promise = Promise.resolve() | |
for (let end=2; end<=segments.length; end++) { | |
const tmpDirpath = segments.slice(0, end).join('/') | |
// chain promises | |
promise = promise | |
.then(() => fsExists(tmpDirpath)) | |
.then((exists) => exists ? 1: fsMkdir(tmpDirpath)) | |
} | |
return promise | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment