Introduction
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.
Using process.cwd()
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 directory
console.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:
- Building CLI tools that run from anywhere
- Resolving user-specified file paths
- Logging or debugging where your app was started
Understanding __dirname
__dirname
is a global variable in CommonJS modules that always points to the directory where the script file resides.
// prints the directory of this file
console.log(__dirname);
Note: In ES modules (
.mjs
),__dirname
is not available. You can emulate it:
import { dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
Choosing Between cwd and dirname
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()
.
Resolving Paths with path Module
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 joins -
path.resolve
to get an absolute path
Common Pitfalls and Fixes
- Forgetting to handle ES modules
- Assuming cwd never changes
- Using hardcoded paths
Always test your code from different folders and use path helpers.
Real-World Examples
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.
Conclusion
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.
Top comments (0)