
Mateen Kiani
Published on Mon Jul 14 2025·2 min read

It is common to need the path to your current working directory when working with Node.js scripts. A less obvious detail is understanding the difference between the folder where your script lives (__dirname) and where the process started (process.cwd()). How do you know which one to use in your project?
By mastering these two methods, you can manage file paths reliably and avoid broken imports or missing assets. The examples below will help you pick the right tool for your task.
process.cwd() returns the directory from which you launched the Node.js process. It is dynamic and can change if you use process.chdir().
// prints the current working directoryconsole.log(process.cwd());
Tip: If you run your script from different folders,
process.cwd()lets you adapt paths relative to the user’s location.
Use cases:
__dirname is a global variable in CommonJS modules that always points to the directory where the script file resides.
// prints the directory of this fileconsole.log(__dirname);
Note: In ES modules (
.mjs),__dirnameis not available. You can emulate it:
import { dirname } from 'path';import { fileURLToPath } from 'url';const __dirname = dirname(fileURLToPath(import.meta.url));
Choosing which to use depends on your needs:
| Use case | Method |
|---|---|
| Script assets (e.g., views, config next to code) | __dirname |
| User files or CLI paths | process.cwd() |
Mixing them helps in complex apps. For example, you may load config with __dirname while processing data from a user path via process.cwd().
Combine these values with Node’s path module for safe resolution:
import path from 'path';const configPath = path.join(__dirname, 'config', 'default.json');const output = path.resolve(process.cwd(), 'output', 'result.txt');console.log(configPath);console.log(output);
path.join for simple joinspath.resolve to get an absolute pathAlways test your code from different folders and use path helpers.
You might want to list files relative to script location. See how to list files in a directory.
Or check if a file exists before reading it: check if file exists.
Knowing how to get the current directory in Node.js solves many path-related headaches. Use process.cwd() for user-driven paths and __dirname for script assets. Pair them with the path module and test under different scenarios. With this knowledge, you can build robust file operations and avoid surprises.
