🔍 What Are Global Objects in Node.js?
Global objects are built-in objects in Node.js that you can access anywhere in your code without importing any modules. They provide useful functionalities like logging, timing, process information, and binary data handling.
🖥️ console: Logging and Debugging
The console object is used to log information and debug your application.
Example:
console.log('Hello, Node.js!');
console.error('This is an error message');
console.warn('This is a warning');
console.log is for normal messages, console.error is for errors, and console.warn is for warnings.
⏱️ setTimeout and setInterval: Timing Functions
setTimeout and setInterval help run code after a delay or repeatedly.
Example:
setTimeout(() => {
console.log('This runs after 2 seconds');
}, 2000);
let count = 0;
const interval = setInterval(() => {
console.log(`Count: ${count}`);
count++;
if (count > 3) clearInterval(interval);
}, 1000);
setTimeout runs a function once after a delay, setInterval runs repeatedly until cleared.
🗂️ process: Application Information and Control
The process object provides information about the running Node.js process and lets you interact with the system.
Example:
console.log('Process ID:', process.pid);
console.log('Node Version:', process.version);
console.log('Current Directory:', process.cwd());
You can check the process ID, Node.js version, and current working directory.
🧩 Buffer: Handling Binary Data
Buffer allows you to handle raw binary data, useful for reading files or working with network streams.
Example:
const buf = Buffer.from('Hello, Node.js');
console.log(buf); // Binary representation
console.log(buf.toString()); // Convert back to string
Buffers let you store and manipulate bytes efficiently.
🔄 setImmediate and process.nextTick: Event Loop Control
These functions control when a function runs relative to the event loop.
Example:
setImmediate(() => console.log('Runs after I/O events'));
process.nextTick(() => console.log('Runs before other I/O events'));
process.nextTick runs before any I/O events, while setImmediate runs after I/O events.
🛠️ module and require: Module Management
Module and require are global objects used to import and manage modules.
Example:
const fs = require('fs');
console.log('Current module ID:', module.id);
Require imports modules, module provides info about the current module.
📝 Summary
Node.js provides several global objects like console, setTimeout, setInterval, process, Buffer, setImmediate, process.nextTick, module, and require. These objects allow developers to log messages, schedule tasks, manage processes, handle binary data, control the event loop, and work with modules. Using these global objects effectively makes Node.js applications efficient, maintainable, and easier to manage.