Skip to content

Commit

Permalink
Fix fs.promises.watch context stuff
Browse files Browse the repository at this point in the history
Added tests to prevent regression
  • Loading branch information
james-pre committed Dec 24, 2024
1 parent be3f663 commit c7fd4b6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/emulation/promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -951,9 +951,10 @@ export function watch(
options?: fs.WatchOptions | string
): AsyncIterable<promises.FileChangeInfo<string>> | AsyncIterable<promises.FileChangeInfo<Buffer>>;
export function watch<T extends string | Buffer>(this: V_Context, filename: fs.PathLike, options: fs.WatchOptions | string = {}): AsyncIterable<promises.FileChangeInfo<T>> {
const context = this;
return {
[Symbol.asyncIterator](): AsyncIterator<promises.FileChangeInfo<T>> {
const watcher = new FSWatcher<T>(this, filename.toString(), typeof options !== 'string' ? options : { encoding: options as BufferEncoding | 'buffer' });
const watcher = new FSWatcher<T>(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<promises.FileChangeInfo<T>>) => void)[] = [];
Expand Down
17 changes: 17 additions & 0 deletions tests/common/context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});

0 comments on commit c7fd4b6

Please sign in to comment.