diff --git a/ext/node/polyfills/fs.ts b/ext/node/polyfills/fs.ts index 6751c0b115ea02..b5d9a0d37eb910 100644 --- a/ext/node/polyfills/fs.ts +++ b/ext/node/polyfills/fs.ts @@ -3235,7 +3235,28 @@ type watchOptions = { ignore?: IgnoreOption; }; -type watchListener = (eventType: string, filename: string) => void; +type watchListener = ( + eventType: string, + filename: string | Buffer, +) => void; + +// Match Node: `encoding: 'buffer'` returns a Buffer, any other named encoding +// returns the filename re-encoded from utf8. Default ('utf8' or absent) leaves +// the string unchanged. https://github.com/nodejs/node/blob/main/lib/internal/fs/watchers.js +function encodeWatchFilename( + filename: string, + encoding: string | undefined, +): string | Buffer { + if (!encoding || encoding === "utf8" || encoding === "utf-8") { + return filename; + } + const asBuffer = Buffer.from(filename); + if (encoding === "buffer") { + return asBuffer; + } + // deno-lint-ignore prefer-primordials + return asBuffer.toString(encoding as BufferEncoding); +} function watch( filename: string | URL, @@ -3279,6 +3300,7 @@ function watch( validateBoolean(options.persistent, "options.persistent"); } const recursive = options?.recursive || false; + const encoding = options?.encoding; validateIgnoreOption(options?.ignore, "options.ignore"); const ignoreMatcher = createIgnoreMatcher(options?.ignore); const iterator: Deno.FsWatcher = Deno.watchFs(watchPath, { @@ -3303,7 +3325,7 @@ function watch( fsWatcher.emit( "change", convertDenoFsEventToNodeFsEvent(val.kind), - filename, + encodeWatchFilename(filename, encoding), ); }, (e) => { fsWatcher.emit("error", e); diff --git a/tests/node_compat/config.jsonc b/tests/node_compat/config.jsonc index f2269892f2bfcf..ffe366aa4d07eb 100644 --- a/tests/node_compat/config.jsonc +++ b/tests/node_compat/config.jsonc @@ -1201,6 +1201,7 @@ "parallel/test-fs-util-validateoffsetlength.js": {}, "parallel/test-fs-utimes-y2K38.js": {}, "parallel/test-fs-utimes.js": {}, + "parallel/test-fs-watch-encoding.js": {}, "parallel/test-fs-watch-file-enoent-after-deletion.js": {}, "parallel/test-fs-watch-ignore-function.js": {}, "parallel/test-fs-watch-ignore-glob.js": {},