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