UNPKG

@lxf2513/readdir-sync-recursive

Version:

Reads the contents of the directory synchronously and recursively.

39 lines (36 loc) 934 B
import { statSync, readdirSync } from 'node:fs'; import { join, relative } from 'node:path'; import { cwd } from 'node:process'; function isDir(path) { try { return statSync(path).isDirectory(); } catch { return false; } } function index(path, type) { if (!isDir(path)) { return []; } const results = []; function readdir(dir) { try { const result = readdirSync(dir, { encoding: "utf-8" }); for (let i = 0; i < result.length; i++) { const rpath = join(dir, result[i]); const rrpath = relative(path, rpath); const apath = join(cwd(), rpath); const ppath = type === "relativePath" ? rpath : type === "absolutePath" ? apath : rrpath; results.push(ppath); if (isDir(rpath)) { readdir(rpath); } } } catch (error) { console.error(error); } } readdir(path); return results; } export { index as default };