Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท process

Node.js process.cwd() and process.chdir()

Reference for process.cwd() and process.chdir() in Node.js: get and change the working directory, how relative paths resolve, and why cwd differs from __dirname.

process.cwd() returns the current working directory of the Node.js process as an absolute path. It is the directory the process was started from (not where the script file lives) unless something changed it. Relative paths passed to fs functions, path.resolve() and many other APIs are interpreted against this directory.

process.chdir(directory) changes the working directory for the whole process. Both are synchronous.

NODE
console.log(process.cwd());
process.chdir('..');

Try it

Node.js Reading and changing the directory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Errors and the script directory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
process.cwd(): string
process.chdir(directory: string): void
Name Description
directory Path of the directory to switch to. Relative paths are resolved against the current working directory.

Returns: cwd() returns the absolute path as a string; chdir() returns undefined.

Errors: chdir() throws a system error such as ENOENT (does not exist) or ENOTDIR, and ERR_INVALID_ARG_TYPE for a non-string. In worker threads chdir() throws ERR_WORKER_UNSUPPORTED_OPERATION.

Usage notes

  • cwd is not the script folder. It depends on where the user ran the command. To load files that ship next to your code, build paths from import.meta.dirname (ESM) or __dirname (CommonJS).
  • Avoid chdir() in libraries and servers. It changes global state for the whole process and for every pending relative path; prefer absolute paths via path.resolve().
  • Handy for CLIs. A tool that accepts a --cwd option can change directory once at startup and treat the rest of its work as relative.
  • Child processes inherit the cwd by default; set the cwd option to start them elsewhere without moving your own process.
  • Deleted directories. If the cwd is removed while the process runs, process.cwd() may throw ENOENT.
  • Symlinks. cwd() reports the resolved physical path on most systems, so it can differ from what the shell prompt shows.
  • Not available in workers. chdir() is unsupported in worker_threads; reading cwd() works.