Last active
March 5, 2021 15:20
-
-
Save MattStypa/e1ac4ce4bcf09c2687b69aef21d50fde to your computer and use it in GitHub Desktop.
Create a directory at any depth
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 fs = require('fs/promises'); | |
const nodePath = require('path'); | |
async function exists(path) { | |
try { | |
await fs.stat(nodePath.resolve(path)); | |
return true; | |
} catch(error) { | |
if (error.code !== 'ENOENT') throw error; | |
return false; | |
} | |
} | |
async function makeDirectory(path) { | |
const paths = nodePath | |
.resolve(path) | |
.split(nodePath.sep) | |
.map((path, index, paths) => paths.slice(0, paths.length - index).join(nodePath.sep)) | |
.filter((path) => path); | |
let depth; | |
for (let i = 0; i < paths.length; i++) { | |
depth = i; | |
if (await exists(paths[i])) break; | |
} | |
if (!depth) return; | |
for (let i = depth; i > 0; i--) { | |
try { | |
await fs.mkdir(paths[i - 1]); | |
} catch(error) { | |
if (error.code !== 'EEXIST') throw error; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment