Discover how to stop your Node.js scripts from breaking just because you ran them from the wrong folder!
Why process.cwd and __dirname in Node.js? - Purpose & Use Cases
Imagine you write a Node.js script that reads files using relative paths. You run it from different folders, and suddenly your script can't find the files anymore.
Manually guessing or hardcoding file paths is confusing and breaks easily when you move or run your code from different places. It's like trying to find your keys in a dark room without a flashlight.
Using process.cwd() and __dirname gives you reliable ways to know exactly where your code is running and where your files are, so you can build paths that always work.
const data = require('./data.json'); // breaks if run from another folder
const path = require('path'); const data = require(path.join(__dirname, 'data.json')); // always works
You can write Node.js scripts that find and load files correctly no matter where you run them from.
When building a tool that reads configuration files or templates, using __dirname ensures your tool always finds those files even if users run it from different folders.
process.cwd() tells you the current working folder where the script was started.
__dirname tells you the folder where the current script file lives.
Using them helps avoid broken file paths and makes your code more reliable.