Global Objects
Node.js provides several global objects that are accessible across the runtime without needing to import any modules. Here are some key ones with examples and descriptions:
global
: This is the global object in Node.js, similar towindow
in a browser. Variables attached toglobal
are accessible everywhere in the application.global.myVar = "Hello, World!"; console.log(global.myVar); // Output: Hello, World!
- Use: It allows access to variables across files, though it is generally discouraged for maintaining clean code.
process
: This object provides information about and control over the current Node.js process. It includes methods and properties that allow interaction with the operating system.console.log(process.version); // Output: Node.js version console.log(process.argv); // Output: Array of command-line arguments
- Use: Used for accessing environment variables, controlling the runtime, and exiting the process gracefully.
__dirname
: A string that represents the directory name of the current module.console.log(__dirname); // Output: Path to the current directory
- Use: Useful for constructing absolute paths for files within the project.
__filename
: Similar to__dirname
, but it represents the absolute path to the current module file.console.log(__filename); // Output: Path to the current file
- Use: Handy for logging the current script’s path and accessing the file.
module
andexports
: In Node.js, each file is treated as a module. Themodule
object represents the current module, andexports
is an object that modules use to export functions or data.module.exports = { sayHello: function () { return "Hello!"; }, };
- Use: Allows modularization by defining which objects or functions are accessible outside of the file.
Buffer
: A global object in Node.js that allows handling of binary data directly.const buffer = Buffer.from("Hello, World!"); console.log(buffer.toString()); // Output: Hello, World!
- Use: Primarily for working with raw binary data, often in streams and file handling.
setTimeout
,clearTimeout
,setInterval
,clearInterval
: These are timer functions similar to those in the browser, but they work at the Node.js server level.const timerId = setTimeout(() => { console.log("This will run after 1 second."); }, 1000); clearTimeout(timerId); // Prevents the timer from executing
- Use: Useful for scheduling operations like delays or repeated tasks on the server.
Each of these global objects offers unique functionality that’s crucial for working within Node.js, from managing environment settings to handling binary data and scheduling.