Perf: record relative dir instead of calc

This commit is contained in:
SukkaW 2024-08-15 03:58:38 +08:00
parent 30c1fb1fa8
commit d0154e1bc8

View File

@ -1,5 +1,5 @@
import fsp from 'fs/promises'; import fsp from 'fs/promises';
import { sep, relative } from 'path'; import { sep } from 'path';
interface TreeFileType { interface TreeFileType {
type: 'file', type: 'file',
@ -22,11 +22,11 @@ type VoidOrVoidArray = void | VoidOrVoidArray[];
export const treeDir = async (rootPath: string): Promise<TreeTypeArray> => { export const treeDir = async (rootPath: string): Promise<TreeTypeArray> => {
const tree: TreeTypeArray = []; const tree: TreeTypeArray = [];
const walk = async (dir: string, node: TreeTypeArray): Promise<VoidOrVoidArray> => { const walk = async (dir: string, node: TreeTypeArray, dirRelativeToRoot = ''): Promise<VoidOrVoidArray> => {
const promises: Array<Promise<VoidOrVoidArray>> = []; const promises: Array<Promise<VoidOrVoidArray>> = [];
for await (const child of await fsp.opendir(dir)) { for await (const child of await fsp.opendir(dir)) {
const childFullPath = child.parentPath + sep + child.name; const childFullPath = child.parentPath + sep + child.name;
const childRelativeToRoot = relative(rootPath, childFullPath); const childRelativeToRoot = dirRelativeToRoot + sep + child.name;
if (child.isDirectory()) { if (child.isDirectory()) {
const newNode: TreeDirectoryType = { const newNode: TreeDirectoryType = {
@ -36,7 +36,7 @@ export const treeDir = async (rootPath: string): Promise<TreeTypeArray> => {
children: [] children: []
}; };
node.push(newNode); node.push(newNode);
promises.push(walk(childFullPath, newNode.children)); promises.push(walk(childFullPath, newNode.children, childRelativeToRoot));
continue; continue;
} }
if (child.isFile()) { if (child.isFile()) {