Skip to content

Instantly share code, notes, and snippets.

@sistematico
Created December 19, 2022 02:20
Show Gist options
  • Save sistematico/63b59a0b62faead3100f1f5038313194 to your computer and use it in GitHub Desktop.
Save sistematico/63b59a0b62faead3100f1f5038313194 to your computer and use it in GitHub Desktop.
Directory Structure to Object in JavaScript using Node.js
// 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