Created
December 19, 2022 02:20
-
-
Save sistematico/63b59a0b62faead3100f1f5038313194 to your computer and use it in GitHub Desktop.
Directory Structure to Object in JavaScript using Node.js
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
// From original answer here: https://stackoverflow.com/a/18934385/1844007 | |
// ESM Version | |
// Example FileTree: ./json/2022/12/18/data.json | |
import fs from 'fs' | |
let filetree = {} | |
const walkDirectory = (dir, obj) => { | |
const files = fs.readdirSync(dir) | |
for (const key in files) { | |
if (!files.hasOwnProperty(key)) continue | |
const file = files[key] | |
const target = `${dir}/${file}` | |
const stats = fs.statSync(target) | |
if (stats.isFile()) { | |
if (file.endsWith('.json')) { | |
// const name = file.slice(0, -5) | |
// obj[name] = JSON.parse(fs.readFileSync(target)) | |
obj['data'] = JSON.parse(fs.readFileSync(target)) | |
} | |
} else if (stats.isDirectory()) { | |
obj[file] = {} | |
walkDirectory(target, obj[file]) | |
} | |
} | |
} | |
walkDirectory('./json', filetree); | |
console.log(filetree); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment