UNPKG

@lxf2513/readdir-sync-recursive

Version:

Reads the contents of the directory synchronously and recursively.

41 lines (37 loc) 996 B
'use strict'; const node_fs = require('node:fs'); const node_path = require('node:path'); const node_process = require('node:process'); function isDir(path) { try { return node_fs.statSync(path).isDirectory(); } catch { return false; } } function index(path, type) { if (!isDir(path)) { return []; } const results = []; function readdir(dir) { try { const result = node_fs.readdirSync(dir, { encoding: "utf-8" }); for (let i = 0; i < result.length; i++) { const rpath = node_path.join(dir, result[i]); const rrpath = node_path.relative(path, rpath); const apath = node_path.join(node_process.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; } module.exports = index;