Last active
August 4, 2022 06:32
-
-
Save sethdavis512/49af6ad04888721760459a04347406e9 to your computer and use it in GitHub Desktop.
Use object to build directory structure.
This file contains hidden or 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'); | |
// Paths functions from | |
// https://lowrey.me/getting-all-paths-of-an-javascript-object/ | |
function getPaths(root) { | |
let paths = []; | |
let nodes = [{ | |
obj: root, | |
path: [] | |
}]; | |
while (nodes.length > 0) { | |
let n = nodes.pop(); | |
Object.keys(n.obj).forEach(k => { | |
if (typeof n.obj[k] === 'object') { | |
let path = n.path.concat(k); | |
paths.push(path); | |
nodes.unshift({ | |
obj: n.obj[k], | |
path: path | |
}); | |
} | |
}); | |
} | |
return paths; | |
} | |
const rootFolder = process.argv[2] || 'your-project-name'; | |
const directoryStructure = { | |
[rootFolder]: { | |
first: { | |
second: {}, | |
third: { | |
fourth: {} | |
} | |
} | |
} | |
}; | |
const allPaths = getPaths(directoryStructure); | |
allPaths.forEach(path => { | |
const pathName = path.join('/'); | |
fs.mkdirSync(pathName); | |
}); |
So i may have had a little too much fun...
const fs = require('fs-extra');
const awesomeDirectoryStruct = {
RootDirectory: {
'Level-1-Directory': {
'Level-2A-Directory': 'Level-3-And-Final-Directory',
'Level-2B-Directory': {
'Level-3A-Directory': 'Level-4-And-Final-Directory',
'Level-3B-Directory': 'Level-4-And-Final-Directory'
},
'Level-2C-Directory': {
'Level-3-Directory': {
'Level-4-Directory': 'Level-5-And-Final-Directory'
}
}
}
}
}
async function createAwesomeDirectoryStruct(obj) {
const directoriesToCreate = function andThen(bit, path = '') {
return [].concat(
...Object.keys(bit).map(key => {
const value = bit[key];
const tmpPath = `${path}/${key}`;
return typeof value === 'object'
? andThen(value, tmpPath)
: `${tmpPath}/${value}`;
}))
}(obj).map(path => { // this maps the array of paths to an array of promises promises since `fs.mkdirp` is async. (fs.mkdirpSync exists)
return new Promise((resolve, reject) => {
return fs.mkdirp(`${__dirname}${path}`, (error, result) => {
if (error) return reject(error);
return resolve(result)
})
});
});
return await Promise.all(directoriesToCreate); // this '.all' executes an array of promises in parallel and returns when all finish resolving
}
createAwesomeDirectoryStruct(awesomeDirectoryStruct)
😈
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What are you attempting to achieve? Declaring a directory structure as an object?