Node.js Global Objects
Learn about global objects in Node.js, understand console, global This, timers, and other commonly used APIs, and discover how these objects help developers execute JavaScript without importing every feature manually.
1. Introduction to Global Objects
Global objects and APIs are available in the JavaScript environment without requiring us to import them individually. Node.js provides several built-in globals that help developers print messages, schedule operations, access the current execution context, and work with application data.
For example, we can use console.log() directly
in a JavaScript file to display a message in the terminal.
We do not need to import the console object first.
Common Node.js Globals
| Global | Purpose | Example |
|---|---|---|
console |
Displays messages and debugging information. | console.log("Hello"); |
globalThis |
References the global object for the current JavaScript environment. | globalThis.console |
setTimeout() |
Schedules a callback to run after a delay. | setTimeout(callback, 1000) |
setInterval() |
Schedules a callback repeatedly. | setInterval(callback, 1000) |
clearTimeout() |
Cancels a pending timeout. | clearTimeout(timerId) |
clearInterval() |
Stops a repeating interval. | clearInterval(timerId) |
process |
Provides information and controls for the current Node.js process. | process.version |
Buffer |
Works with binary data. | Buffer.from("CIIT") |
2. How Global APIs Work
When Node.js executes a JavaScript file, the runtime provides access to its supported global APIs. The program can use these APIs directly where appropriate.
app.js
console, setTimeout(),
globalThis
Some APIs are provided by Node.js, while others are part of the JavaScript language or are available through the runtime. Their exact behavior depends on the API.
3. The Console Object
The console object provides methods for displaying
information, warnings, errors, and debugging output. It is one
of the most commonly used APIs when learning Node.js.
Example: Display Messages
console.log("Hello Samadhan!");
console.info("Pradnya is learning Node.js.");
console.warn("This is a warning message.");
console.error("This is an error message.");
Execute the Program
node consoleExample.js
Expected Output
Hello Samadhan!
Pradnya is learning Node.js.
This is a warning message.
This is an error message.
Method Explanation
console.log()displays general information.console.info()displays informational messages.console.warn()displays a warning.console.error()displays an error message.
4. The globalThis Object
globalThis is the standard JavaScript way to
reference the global object in the current environment.
In Node.js, it provides access to global properties and APIs
that are available in that environment.
Example: Access Console Through globalThis
globalThis.console.log("Using globalThis in Node.js.");
console.log(
globalThis === global
);
Execute the Program
node globalExample.js
Expected Output in Standard Node.js
Using globalThis in Node.js.
true
Explanation
globalThis.consoleaccesses the console property through the global object.globalis Node.js's traditional global-object reference.- In standard Node.js,
globalThisandglobalreference the same global object.
5. The setTimeout() Function
setTimeout() schedules a callback to run after a
specified delay. The delay is measured in milliseconds.
The callback does not necessarily execute at the exact requested
time; it runs when the event loop can process it.
Example: Display a Delayed Message
console.log("Program started.");
setTimeout(() => {
console.log("Hello Samadhan!");
}, 2000);
console.log("Program continues.");
Execute the Program
node timeoutExample.js
Expected Output Order
Program started.
Program continues.
Hello Samadhan!
Explanation
- The first message is printed immediately.
setTimeout()schedules the callback for approximately two seconds later.- The next synchronous statement runs without waiting for the timeout.
- The callback runs later when the event loop can process it.
setTimeout() does not pause the entire JavaScript
program for the specified delay. It schedules a callback.
6. The setInterval() Function
setInterval() schedules a callback to run repeatedly
at a requested interval. It is useful for recurring tasks,
although the actual timing can vary.
Example: Display a Message Three Times
let count = 0;
const timerId = setInterval(() => {
count++;
console.log("Samadhan's task count:", count);
if (count === 3) {
clearInterval(timerId);
console.log("Task completed.");
}
}, 1000);
Execute the Program
node intervalExample.js
Expected Output
Samadhan's task count: 1
Samadhan's task count: 2
Samadhan's task count: 3
Task completed.
Code Explanation
countstores how many times the callback has run.setInterval()schedules repeated execution.timerIdstores the identifier returned by the timer.clearInterval(timerId)stops future interval callbacks.
7. The Buffer Global
A Buffer is used to work with binary data.
Node.js applications commonly use buffers when processing
file contents, network data, and other byte-based information.
Example: Convert Text into a Buffer
const message = "CIIT";
const bufferData = Buffer.from(message);
console.log("Original Text:", message);
console.log("Buffer Data:", bufferData);
console.log("Buffer Length:", bufferData.length);
console.log("Converted Text:", bufferData.toString());
Execute the Program
node bufferExample.js
Expected Output
Original Text: CIIT
Buffer Data: <Buffer 43 49 49 54>
Buffer Length: 4
Converted Text: CIIT
Explanation
Buffer.from(message)creates a buffer from the text.- The buffer stores the UTF-8 bytes for this ASCII text.
bufferData.lengthreturns the number of bytes.toString()converts the buffer contents back to text.
8. Global APIs vs Imported Modules
Not all Node.js features are globally available. Some APIs,
such as console and Buffer, are
available globally, while other features are accessed through
modules.
| Feature | How to Access | Example |
|---|---|---|
| Console | Global API | console.log("Hello"); |
| Buffer | Global API | Buffer.from("CIIT"); |
| File System | Import the fs module |
const fs = require("node:fs"); |
| HTTP Server | Import the http module |
const http = require("node:http"); |
| Path Utilities | Import the path module |
const path = require("node:path"); |
Example: Import the File System Module
const fs = require("node:fs");
console.log("File system module loaded.");
console.log(typeof fs.readFile);
Expected Output
File system module loaded.
function
The fs module is imported explicitly. Its
readFile method is a function that can be used
to read file contents.
9. Common Mistakes When Using Globals
| Mistake | Why It Happens | Better Approach |
|---|---|---|
| Assuming every API is global | Not all Node.js modules are global. | Import required modules explicitly. |
| Leaving intervals active | Repeated callbacks continue to be scheduled. | Use clearInterval() when finished. |
| Expecting exact timer timing | Callback execution depends on event-loop scheduling. | Treat timer delays as minimum scheduling delays, not exact guarantees. |
| Adding too many global variables | Global names can conflict and make code harder to maintain. | Prefer local variables and module scope. |
| Confusing bytes with characters | UTF-8 characters can require multiple bytes. | Understand how Buffer length is measured. |
10. CIIT Training Institute - Practice Task
Task: Create a Global APIs Demonstration
Create a file named globalPractice.js and
complete these activities:
- Print a welcome message for Samadhan and Pradnya.
- Display the Node.js version using the
processobject. - Convert the text
CIITinto a Buffer. - Display the buffer length.
- Schedule a message using
setTimeout(). - Run the program and inspect its output.
Sample Solution
console.log("Hello Samadhan!");
console.log("Hello Pradnya!");
console.log("Node.js Version:", process.version);
const instituteName = "CIIT";
const instituteBuffer = Buffer.from(instituteName);
console.log("Buffer Length:", instituteBuffer.length);
setTimeout(() => {
console.log("Global APIs practice completed.");
}, 1000);
Expected Output
Hello Samadhan!
Hello Pradnya!
Node.js Version: [your Node.js version]
Buffer Length: 4
Global APIs practice completed.
The Node.js version will vary by computer. The delayed message appears after the synchronous statements have run.
Summary
Node.js global APIs provide useful functionality without requiring an explicit import for every feature. We learned how to use console methods, globalThis, setTimeout, setInterval, timer cancellation, and Buffer. We also compared globally available APIs with modules that must be imported. Practical examples at CIIT TRAINING INSTITUTE help students understand these concepts and prepare for the next topic: the Node.js Process Object.