diff --git a/ext/node/polyfills/_process/process.ts b/ext/node/polyfills/_process/process.ts index 9aa9227094071f..1ea83725cb4de5 100644 --- a/ext/node/polyfills/_process/process.ts +++ b/ext/node/polyfills/_process/process.ts @@ -26,6 +26,7 @@ import { nextTick as _nextTick } from "ext:deno_node/_next_tick.ts"; import { _exiting } from "ext:deno_node/_process/exiting.ts"; import * as fs from "ext:deno_fs/30_fs.js"; import { + denoErrorToNodeError, ERR_INVALID_ARG_TYPE, ERR_INVALID_OBJECT_DEFINE_PROPERTY, } from "ext:deno_node/internal/errors.ts"; @@ -51,7 +52,17 @@ export function chdir(directory: string): void { if (typeof directory !== "string") { throw new ERR_INVALID_ARG_TYPE("directory", "string", directory); } - fs.chdir(directory); + try { + fs.chdir(directory); + } catch (e) { + // Match Node's error shape: code/syscall/path/dest with a libuv-style + // message ("ENOENT: no such file or directory, chdir '' -> ''"). + throw denoErrorToNodeError(e as Error, { + syscall: "chdir", + path: fs.cwd(), + dest: directory, + }); + } } /** https://nodejs.org/api/process.html#process_process_cwd */ diff --git a/tests/node_compat/config.jsonc b/tests/node_compat/config.jsonc index 8ddb94991ed8a2..9a7c0df11948c7 100644 --- a/tests/node_compat/config.jsonc +++ b/tests/node_compat/config.jsonc @@ -2457,6 +2457,7 @@ "parallel/test-process-beforeexit-throw-exit.js": {}, "parallel/test-process-binding-internalbinding-allowlist.js": {}, "parallel/test-process-binding.js": {}, + "parallel/test-process-chdir-errormessage.js": {}, "parallel/test-process-chdir.js": {}, "parallel/test-process-config.js": {}, "parallel/test-process-constants-noatime.js": { diff --git a/tests/unit_node/process_test.ts b/tests/unit_node/process_test.ts index 7f0c6d575ebc4c..ef7bf8b51d96dc 100644 --- a/tests/unit_node/process_test.ts +++ b/tests/unit_node/process_test.ts @@ -76,16 +76,16 @@ Deno.test({ Deno.test({ name: "process.chdir failure", fn() { - assertThrows( + const err = assertThrows( () => { process.chdir("non-existent-directory-name"); }, - Deno.errors.NotFound, - "file", - // On every OS Deno returns: "No such file" except for Windows, where it's: - // "The system cannot find the file specified. (os error 2)" so "file" is - // the only common string here. - ); + Error, + "ENOENT", + ) as Error & { code?: string; syscall?: string; dest?: string }; + assertEquals(err.code, "ENOENT"); + assertEquals(err.syscall, "chdir"); + assertEquals(err.dest, "non-existent-directory-name"); }, });