diff options
author | Marvin Hagemeister <marvin@deno.com> | 2024-07-31 13:07:49 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-07-31 13:07:49 +0200 |
commit | 9e6288ec61922ad34ebb09694b5c444ce9767d21 (patch) | |
tree | 55c65e53ef524bd2899fb32ffadd3becc8a45c98 /ext/node/polyfills/_fs/_fs_watch.ts | |
parent | 1e2581e57b46e5e7512ceb5637d6007db67c3ed4 (diff) |
fix(node/fs/promises): watch should be async iterable (#24805)
The way `fs.watch` works is different in `node:fs/promises` than
`node:fs`. It has a different function signature and it returns an async
iterable instead, see
https://nodejs.org/api/fs.html#fspromiseswatchfilename-options
Fixes https://github.com/denoland/deno/issues/24661
Diffstat (limited to 'ext/node/polyfills/_fs/_fs_watch.ts')
-rw-r--r-- | ext/node/polyfills/_fs/_fs_watch.ts | 53 |
1 files changed, 37 insertions, 16 deletions
diff --git a/ext/node/polyfills/_fs/_fs_watch.ts b/ext/node/polyfills/_fs/_fs_watch.ts index 9e02ea0f1..acdaff800 100644 --- a/ext/node/polyfills/_fs/_fs_watch.ts +++ b/ext/node/polyfills/_fs/_fs_watch.ts @@ -155,22 +155,43 @@ export function watch( return fsWatcher; } -export const watchPromise = promisify(watch) as ( - & (( - filename: string | URL, - options: watchOptions, - listener: watchListener, - ) => Promise<FSWatcher>) - & (( - filename: string | URL, - listener: watchListener, - ) => Promise<FSWatcher>) - & (( - filename: string | URL, - options: watchOptions, - ) => Promise<FSWatcher>) - & ((filename: string | URL) => Promise<FSWatcher>) -); +export function watchPromise( + filename: string | Buffer | URL, + options?: { + persistent?: boolean; + recursive?: boolean; + encoding?: string; + signal?: AbortSignal; + }, +): AsyncIterable<{ eventType: string; filename: string | Buffer | null }> { + const watchPath = getValidatedPath(filename).toString(); + + const watcher = Deno.watchFs(watchPath, { + recursive: options?.recursive ?? false, + }); + + if (options?.signal) { + options?.signal.addEventListener("abort", () => watcher.close()); + } + + const fsIterable = watcher[Symbol.asyncIterator](); + const iterable = { + async next() { + const result = await fsIterable.next(); + if (result.done) return result; + + const eventType = convertDenoFsEventToNodeFsEvent(result.value.kind); + return { + value: { eventType, filename: basename(result.value.paths[0]) }, + done: result.done, + }; + }, + }; + + return { + [Symbol.asyncIterator]: () => iterable, + }; +} type WatchFileListener = (curr: Stats, prev: Stats) => void; type WatchFileOptions = { |