These help you find out where your program is running from. This is useful when you want to work with files or folders in your project.
process.cwd and __dirname in Node.js
process.cwd() __dirname
process.cwd() returns the current working directory where you started the Node.js process.
__dirname is a variable that holds the directory name of the current script file.
console.log(process.cwd())
console.log(__dirname)
const path = require('path'); console.log(path.join(__dirname, 'data', 'file.txt'))
This program shows the difference between process.cwd() and __dirname. It also builds a path to a file named example.txt located in the same folder as the script.
const path = require('path'); console.log('Current working directory:', process.cwd()); console.log('Current script directory:', __dirname); const filePath = path.join(__dirname, 'example.txt'); console.log('Path to example.txt:', filePath);
process.cwd() can change if you use process.chdir() to change folders during runtime.
__dirname is fixed to the script file location and does not change.
Use path.join() to safely build file paths that work on all operating systems.
process.cwd() tells you where you started your Node.js program.
__dirname tells you where the current script file lives.
Both help you work with files and folders in your project safely and clearly.