UNPKG

@ou-imdt/utils

Version:

Utility library for interactive media development

25 lines (22 loc) 974 B
import { readdir, writeFile } from 'node:fs/promises'; import { join, sep, parse } from 'path'; import getObjectProperty from '../getObjectProperty.js'; import setObjectProperty from '../setObjectProperty.js'; export default async function createDirTreeJSON(path, options = {}) { const { filename = 'listing', recursive = true } = options; const files = await readdir(path, { recursive }); const list = files.reduce((list, path) => { const { dir, base, ext } = parse(path); if (ext === '') { // dot notation will fall over if dirnames include dots (unlikely)... bracket notation should be ok... setObjectProperty(list, path.split(sep).map(value => `[${value}]`).join(''), {}); } else { const target = getObjectProperty(list, dir.split(sep).join('.')); target.files ??= []; target.files.push(base); } return list; }, {}); // console.log(list); writeFile(join(path, `${filename}.json`), JSON.stringify(list)); }