0
0
Node.jsframework~15 mins

process.cwd and __dirname in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding process.cwd() and __dirname in Node.js
📖 Scenario: You are creating a simple Node.js script that needs to work with file paths. To do this correctly, you must understand how to get the current working directory and the directory of the script file itself.
🎯 Goal: Build a Node.js script that shows the difference between process.cwd() and __dirname by storing their values in variables and then using them.
📋 What You'll Learn
Create a variable called currentWorkingDir that stores the value of process.cwd().
Create a variable called scriptDir that stores the value of __dirname.
Write a function called showDirectories that returns an object with currentWorkingDir and scriptDir as properties.
Export the showDirectories function using module.exports.
💡 Why This Matters
🌍 Real World
When working with files in Node.js, knowing the current working directory and the script's directory helps you build correct file paths. This avoids errors when your program runs from different folders.
💼 Career
Many Node.js jobs require handling file paths correctly. Understanding process.cwd() and __dirname is essential for writing reliable server scripts, build tools, and CLI applications.
Progress0 / 4 steps
1
Create variables for directories
Create a variable called currentWorkingDir and set it to process.cwd(). Then create a variable called scriptDir and set it to __dirname.
Node.js
Need a hint?

Use const to create variables. process.cwd() gives the current working directory. __dirname gives the directory of the current script.

2
Create a function to return directories
Create a function called showDirectories that returns an object with properties currentWorkingDir and scriptDir using the variables you created.
Node.js
Need a hint?

Define a function with function showDirectories(). Return an object with the two variables as properties.

3
Export the function
Export the showDirectories function using module.exports so other files can use it.
Node.js
Need a hint?

Use module.exports = { showDirectories } to export the function.

4
Add a comment explaining the difference
Add a comment at the top of the file explaining in simple words the difference between process.cwd() and __dirname.
Node.js
Need a hint?

Write two simple comments starting with // explaining each one in a friendly way.