Performance: process.cwd and __dirname
This concept affects how file paths are resolved during runtime, impacting module loading speed and script execution consistency.
Jump into concepts and practice - no test required
const path = require('path'); const filePath = path.join(__dirname, 'data', 'file.txt');
const path = require('path'); const filePath = path.join(process.cwd(), 'data', 'file.txt');
| Pattern | Path Stability | File System Calls | Error Risk | Verdict |
|---|---|---|---|---|
| Using process.cwd() | Variable depending on run location | Potentially more calls due to retries | Higher risk of path errors | [X] Bad |
| Using __dirname | Stable and fixed to script location | Minimal calls, direct path | Low risk of errors | [OK] Good |
process.cwd() return in a Node.js program?process.cwd() purposeprocess.cwd() returns the current working directory where the Node.js process was started, not the script location.__dirname__dirname gives the script's folder, which is different from the working directory if you run the script from another folder.process.cwd() = start folder [OK]process.cwd() with __dirname__dirname is a Node.js global variable that holds the directory path of the current script file.process.cwd() returns the working directory, not script folder. The others are not valid Node.js properties or functions.__dirname = script folder [OK]/home/user/projects with script located at /home/user/projects/app/server.js:
console.log(process.cwd()); console.log(__dirname);What will be the output?
process.cwd() output/home/user/projects, process.cwd() returns this folder.__dirname output/home/user/projects/app/server.js, so __dirname returns /home/user/projects/app./app/index.js and ran it from /app folder:
console.log(process.dirName);What will happen when you run this script?
process.dirName is not a valid property in Node.js. The correct property is __dirname.process does not throw an error, but since process is an object, process.dirName is undefined. However, trying to log undefined prints 'undefined' without error.process.dirName is undefined, console.log prints 'undefined'. No ReferenceError occurs.config.json located in the same folder as your script /project/src/app.js. You run the script from /project folder. Which code snippet correctly builds the path to config.json to read it safely regardless of where you run the script?/project/src/app.js and config.json is in the same folder /project/src.__dirname__dirname gives the script folder regardless of where you run the script, so joining __dirname with config.json correctly points to the file.process.cwd() which is /project, so it looks for /project/config.json (wrong folder). const configPath = './config.json'; is relative and depends on run folder, risky. const configPath = process.cwd() + '/src/config.json'; hardcodes path and may break on different OS or run folders.