Skip to content

Instantly share code, notes, and snippets.

@kapraran
Created March 2, 2019 17:55
Show Gist options
  • Save kapraran/52949ffe13bd6dc6979ee56f2d08ceac to your computer and use it in GitHub Desktop.
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.
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