From c7fd4b660251fc3812a9500316a8fcb4138678e0 Mon Sep 17 00:00:00 2001 From: James Prevett Date: Mon, 23 Dec 2024 19:10:56 -0600 Subject: [PATCH] Fix `fs.promises.watch` context stuff Added tests to prevent regression --- src/emulation/promises.ts | 3 ++- tests/common/context.test.ts | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/emulation/promises.ts b/src/emulation/promises.ts index 6a6be1a3..c6d1e211 100644 --- a/src/emulation/promises.ts +++ b/src/emulation/promises.ts @@ -951,9 +951,10 @@ export function watch( options?: fs.WatchOptions | string ): AsyncIterable> | AsyncIterable>; export function watch(this: V_Context, filename: fs.PathLike, options: fs.WatchOptions | string = {}): AsyncIterable> { + const context = this; return { [Symbol.asyncIterator](): AsyncIterator> { - const watcher = new FSWatcher(this, filename.toString(), typeof options !== 'string' ? options : { encoding: options as BufferEncoding | 'buffer' }); + const watcher = new FSWatcher(context, filename.toString(), typeof options !== 'string' ? options : { encoding: options as BufferEncoding | 'buffer' }); // A queue to hold change events, since we need to resolve them in the async iterator const eventQueue: ((value: IteratorResult>) => void)[] = []; diff --git a/tests/common/context.test.ts b/tests/common/context.test.ts index 5f782fff..35684adf 100644 --- a/tests/common/context.test.ts +++ b/tests/common/context.test.ts @@ -16,4 +16,21 @@ suite('Context', () => { test('break-out fails', () => { assert.deepEqual(c_fs.readdirSync('/../../'), ['example.txt']); }); + + test('watch should consider context', async () => { + let lastFile: string, + events = 0; + const watcher = c_fs.promises.watch('/', { recursive: true }); + + (async () => { + for await (const event of watcher) { + lastFile = event.filename!; + if (++events == 2) return; + } + })(); + await c_fs.promises.writeFile('/xpto.txt', 'in real root'); + assert.strictEqual(lastFile!, 'xpto.txt'); + await c_fs.promises.unlink('/xpto.txt'); + assert.strictEqual(lastFile, 'xpto.txt'); + }); });