import fs from 'fs'; import path from 'path'; export async function readFile(path: string, encoding: BufferEncoding = 'utf-8'): Promise { return new Promise((resolve, reject) => { fs.readFile(path, { encoding }, (err, data) => { if (err) return reject(err); try { resolve(data.toString()); } catch (e) { reject(e); } }); }); } export async function readJsonFile(path: string, encoding: BufferEncoding = 'utf-8'): Promise { return new Promise(async (resolve, reject) => { try { resolve(JSON.parse( await readFile(path, encoding) ) as T); } catch (e) { reject(e); } }); } export function readDir(dir: string): Promise { return new Promise((resolve, reject) => { fs.readdir(dir, { withFileTypes: true }, (err, list) => { if (err) return reject(err); resolve(list); }); }); } export function readJsonDir(dir: string, filenameProperty?: string): Promise { return new Promise((resolve, reject) => { fs.readdir(dir, { withFileTypes: true }, async (err, list) => { if (err) return reject(err); const arr: T[] = []; for (const e of list.filter(e => e.isFile() && e.name.match(/\.json$/))) { const json: any = await readJsonFile(path.resolve(dir, e.name)); if (typeof filenameProperty === 'string') { json[filenameProperty] = e.name; } arr.push(json); } resolve(arr); }); }); } export function getSubdirNames(dir: string): Promise { return new Promise((resolve, reject) => { fs.readdir(dir, { withFileTypes: true }, async (err, list) => { if (err) return reject(err); resolve(list.filter(e => e.isDirectory()).map(e => e.name)); }); }); }