process.cwd() return compared to __dirname in a Node.js script?process.cwd() gives the current working directory where you started the Node.js process, which can be different from the script's location. __dirname always gives the directory path of the script file itself.
project/
app/
script.jsIf you run
node app/script.js from the project folder, what will console.log(process.cwd()) and console.log(__dirname) output inside script.js?console.log(process.cwd()); console.log(__dirname);
Running node app/script.js from project means process.cwd() is /project. The __dirname inside script.js is the folder containing the script, /project/app.
__dirname in a Node.js ES module (using type: 'module' in package.json)?In ES modules, __dirname is not available by default and using it causes a ReferenceError. You must use other ways like import.meta.url to get the directory.
/home/user/project/utils/helper.js and runs it from /home/user folder:const path = require('path');
console.log(path.join(process.cwd(), 'utils', 'helper.js'));
console.log(path.join(__dirname, 'helper.js'));What will be the output and what problem might occur?
process.cwd() returns the folder where the command was run (/home/user), so joining it with utils/helper.js points to /home/user/utils/helper.js, which likely does not exist. __dirname correctly points to the script folder /home/user/project/utils.
changeDir.js located at /app/scripts/changeDir.js.console.log('Before:', process.cwd());
process.chdir('/');
console.log('After:', process.cwd());
console.log('__dirname:', __dirname);If you run
node scripts/changeDir.js from /app, what will be the output?process.cwd() initially is /app because you ran the command there. After process.chdir('/'), the working directory changes to root /. __dirname remains the directory of the script file /app/scripts and does not change.