From d739fcb19fb5952a0c1cd9a7c7f1e0a32b3d52b5 Mon Sep 17 00:00:00 2001 From: JrMasterModelBuilder Date: Mon, 2 Oct 2023 23:44:05 -0400 Subject: [PATCH] Added walker abort option --- src/util.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/util.ts b/src/util.ts index 3b05782..74bc6cd 100644 --- a/src/util.ts +++ b/src/util.ts @@ -22,6 +22,15 @@ export interface IFsWalkOptions { ignoreUnreadableDirectories?: boolean; } +export interface IFsWalkSignal { + /** + * Option to abort walker while walking. + * + * @default false + */ + abort?: boolean; +} + const {O_WRONLY, O_SYMLINK} = fsConstants; export const fsLchmodSupported = !!O_SYMLINK; export const fsLutimesSupported = !!O_SYMLINK; @@ -279,24 +288,29 @@ export async function fsLstatExists(path: string) { * @param base Directory path. * @param itter Callback for each entry. * @param options Walk options. + * @param signal Walk signal. */ export async function fsWalk( base: string, itter: (path: string, stat: Stats) => Promise, - options: Readonly = {} + options: Readonly = {}, + signal: IFsWalkSignal = {} ) { const {ignoreUnreadableDirectories} = options; const stack = (await fsReaddir(base)).reverse(); - while (stack.length) { + while (!signal.abort && stack.length) { const entry = stack.pop() as string; const fullPath = pathJoin(base, entry); // eslint-disable-next-line no-await-in-loop const stat = await fsLstat(fullPath); + if (signal.abort) { + break; + } // Callback, possibly stop recursion on directory. // eslint-disable-next-line no-await-in-loop const recurse = await itter(entry, stat); - if (recurse === null) { + if (signal.abort || recurse === null) { break; } if (recurse === false || !stat.isDirectory()) { @@ -319,6 +333,9 @@ export async function fsWalk( throw err; } } + if (signal.abort) { + break; + } for (let i = subs.length; i--; ) { stack.push(pathJoin(entry, subs[i])); }