Node.js: Code Outside the Browser / Node.js Fundamentals

Global objects (__dirname, __filename, console, etc.)

Node.js provides certain global variables and functions that you can use anywhere in your code — no need to import anything.

They’re like tools Node.js gives you for free to make your life easier.

🏠 __dirname

  • 🔹 Stands for "directory name"

  • 📍 Gives the absolute path of the folder where your current file is located

Example:

console.log(__dirname);
C:\Users\codeveda\Projects\node-basics

📄 __filename

  • 🔹 Stands for "file name"

  • 📍 Gives the absolute path of the current file you’re running

Example:

console.log(__filename);
C:\Users\codeveda\Projects\node-basics\index.js

✅ Great for logging file paths or doing operations like reading the current file.


🖨️ console

  • 🔹 Same as in browsers — lets you print output, debug, and log messages

Common uses:

console.log("Hello codeveda!");
console.error("This is an error");
console.warn("This is a warning");

With colors (how it usually appears):

  • console.log → plain white (or default terminal color)

  • console.error → usually red

  • console.warn → usually yellow

✅ Super useful during debugging, tracking output, and testing code.


⏰ setTimeout() — Run once after a delay

📌 What it does:

  • Executes a function ONCE after a given delay (in milliseconds)

✅ Syntax:

setTimeout(callbackFunction, delayInMilliseconds);
setTimeout(() => {
  console.log("This prints after 2 seconds");
}, 2000);

💡 Real-Life Analogy:

Think of setting a reminder on your phone to ring once after 2 minutes. That’s setTimeout.


🔁 setInterval() — Run repeatedly at fixed intervals

📌 What it does:

  • Executes a function repeatedly every X milliseconds

✅ Syntax:

setInterval(callbackFunction, intervalInMilliseconds);
setInterval(() => {
  console.log("This prints every 1 second");
}, 1000);

💡 Real-Life Analogy:

Like a clock ticking every second — that’s setInterval


📚 process

  • Gives information about the current Node.js process (like OS info, environment variables, etc.)

Example:

console.log(process.env.USERNAME); // prints your system's username
console.log(process.argv);         // shows command-line argument

🧪 Summary Table

Global Object

What it Does

Example

__dirname

Full path to folder

console.log(__dirname)

__filename

Full path to file

console.log(__filename)

console

Logs to terminal

console.log("Hi")

setTimeout

Delays execution

setTimeout(..., 1000)

process

Info about app/system

process.argv, process.env