0
0
Node.jsframework~5 mins

process.cwd and __dirname in Node.js - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does process.cwd() return in Node.js?

process.cwd() returns the current working directory from where the Node.js process was started. It shows the folder path you are 'in' when you run your script.

Click to reveal answer
beginner
What is __dirname in Node.js?

__dirname is a variable that holds the directory path of the current JavaScript file. It tells you where the file itself lives on your computer.

Click to reveal answer
intermediate
How do process.cwd() and __dirname differ?

process.cwd() shows the folder where you started the Node.js program.<br>__dirname shows the folder where the current script file is located.<br>They can be different if you run the script from another folder.

Click to reveal answer
intermediate
Why might process.cwd() and __dirname be different?

Because you can run a Node.js script from any folder. process.cwd() is where you ran the command, but __dirname is where the script file lives. For example, running node ./scripts/app.js from your home folder means process.cwd() is your home folder, but __dirname is the scripts folder.

Click to reveal answer
beginner
How can you use __dirname to load a file relative to the current script?
<p>You can combine <code>__dirname</code> with <code>path.join()</code> to build a path to a file in the same folder or a subfolder. For example:<br><code>const path = require('path');<br>const filePath = path.join(__dirname, 'data.txt');</code></p>
Click to reveal answer
What does process.cwd() return?
AThe folder where the current script file is located
BThe user's home directory
CThe folder where the Node.js process was started
DThe root directory of the system
What does __dirname represent?
AThe folder where the Node.js process was started
BThe folder where the current script file is located
CThe temporary files directory
DThe user's home directory
If you run node ./scripts/app.js from your home folder, what will process.cwd() return?
AThe <code>scripts</code> folder path
BThe root folder path
CThe <code>app.js</code> file path
DThe home folder path
Which Node.js module helps safely join paths with __dirname?
Apath
Bhttp
Cfs
Dos
Why is it better to use __dirname instead of process.cwd() when loading files relative to the script?
ABecause <code>process.cwd()</code> changes depending on where you run the script
BBecause <code>__dirname</code> is always the root folder
CBecause <code>process.cwd()</code> is slower
DBecause <code>__dirname</code> is a function
Explain the difference between process.cwd() and __dirname in Node.js.
Think about where you run the command vs where the file lives.
You got /3 concepts.
    How would you use __dirname to load a file named 'config.json' located in the same folder as your script?
    Combine __dirname with path.join for safe file paths.
    You got /3 concepts.