Lesson 10 of 50 – Node.js Global Objects
20% Completed
20%

Node.js Global Objects

Global objects in Node.js are available in different parts of a program without requiring us to import them explicitly. They provide useful features for working with values, timers, environment information, and more.

In simple words: A global object or function can be accessed directly in your Node.js program without importing a separate module for it.

1. What Are Global Objects?

JavaScript running in Node.js provides several globally available objects and functions. Some common examples are:

  • console – displays messages and debugging information.
  • process – provides information about the current Node.js process.
  • global – refers to the global object in Node.js.
  • setTimeout() – schedules a callback to run after a delay.
  • setInterval() – schedules a callback repeatedly.
  • Buffer – works with binary data.
  • URL – represents and parses URLs.

2. The console Object

The console object is used to display messages, errors, warnings, and debugging information in the terminal.

Example: Using console
console.log("Hello Node.js");

console.warn("This is a warning");

console.error("This is an error");

console.table([
    { name: "Amit", age: 20 },
    { name: "Rahul", age: 22 }
]);

Output examples:

Hello Node.js
This is a warning
This is an error

The console.table() method displays the supplied data in a table-like format. Warning and error messages may have different visual styling in the terminal.

3. The process Object

The process object provides information about the currently running Node.js process. It can be used to read environment variables, access command-line arguments, and inspect runtime information.

Example: Process Information
console.log("Node.js version:", process.version);

console.log("Operating system:", process.platform);

console.log("Process ID:", process.pid);

console.log("Current folder:", process.cwd());

Possible output:

Node.js version: v22.x.x
Operating system: win32
Process ID: 12345
Current folder: C:\Projects\NodeApp
Your output will vary depending on your Node.js version, operating system, process ID, and project folder.

4. The global Object

The global object is the global object in Node.js. Properties added to it can be accessed throughout the same JavaScript environment.

Example: Using global
global.appName = "My Node App";

console.log(global.appName);

Output:

My Node App

Although this works, avoid adding unnecessary properties to the global object because they can cause naming conflicts in larger applications.

5. The __dirname Variable

In a CommonJS JavaScript file, __dirname contains the absolute path of the directory containing the current file.

Example: Using __dirname
console.log(__dirname);

Possible output:

C:\Projects\NodeApp
Important: __dirname is available directly in CommonJS files. It is not automatically defined in ES Modules. ES Modules can derive the current file path using import.meta.url.

6. The __filename Variable

In CommonJS, __filename contains the absolute path of the current JavaScript file, including its filename.

Example: Using __filename
console.log(__filename);

Possible output:

C:\Projects\NodeApp\app.js

Remember the difference: __dirname gives the directory path, while __filename gives the full file path. Both are CommonJS-specific variables.

7. The setTimeout() Function

The setTimeout() function schedules a callback to execute after a specified delay in milliseconds.

Example: setTimeout()
console.log("Start");

setTimeout(function() {
    console.log("This message appears later");
}, 2000);

console.log("End");

Output order:

Start
End
This message appears later

The delay is 2000 milliseconds, or approximately two seconds. The callback may run later than the specified delay if the event loop is busy.

8. The setInterval() Function

The setInterval() function repeatedly runs a callback after each interval until the interval is cleared.

Example: setInterval()
let count = 1;

const timer = setInterval(function() {
    console.log("Count:", count);

    count++;

    if (count > 3) {
        clearInterval(timer);
    }
}, 1000);

Output:

Count: 1
Count: 2
Count: 3

The clearInterval() function stops the repeated execution of the interval callback.

9. The Buffer Object

A Buffer is used to work with binary data, such as data read from files or received over a network.

Example: Using Buffer
const data = Buffer.from("Hello");

console.log(data);
console.log(data.toString());

Output:

<Buffer 48 65 6c 6c 6f>
Hello

Buffer.from() converts the text into a buffer. The toString() method converts the buffer's contents back into text.

10. The URL Object

The global URL class allows us to create and inspect URLs without importing a separate module.

Example: Using URL
const website = new URL("https://example.com:8080/products?id=10");

console.log(website.hostname);
console.log(website.port);
console.log(website.pathname);
console.log(website.searchParams.get("id"));

Output:

example.com
8080
/products
10

11. Summary of Global Objects

Object or Function Purpose
console Display messages and debugging information.
process Access information about the current Node.js process.
global Access the Node.js global object.
setTimeout() Schedule a callback after a delay.
setInterval() Schedule repeated callback execution.
Buffer Work with binary data.
URL Parse and work with URLs.
__dirname Directory of the current file in CommonJS.
__filename Full file path in CommonJS.

12. Practical Assignment

Practice Task
Create a Node.js program that uses global objects and functions.
  1. Print a welcome message using console.log().
  2. Display the Node.js version using process.version.
  3. Display the current working directory using process.cwd().
  4. Display a message after two seconds using setTimeout().
  5. Create a buffer from the text "Soopro Pathshala" and print it as text.
  6. Create a URL and print its hostname.

Hint:

const data = Buffer.from("Soopro Pathshala");
console.log(data.toString());

🧠 Quiz – Node.js Global Objects

Select the correct answer for each question.

1. Which object provides information about the current Node.js process?



2. Which function schedules a callback to run after a delay?



3. Which object is used to work with binary data in Node.js?