CLOSE

Node.js provides several objects and functions that are available in every module without needing to import them. These are known as global objects. Here are some of the most important ones:

  • global
  • process
  • Buffer
  • __dirname and __filename
  • require, module, and exports
  • setTimeout, setInterval, clearTimeout, clearInterval, setImmediate, clearImmediate
  • console

global

In Node.js, the global object is analogous to the browser’s window object—it’s the top-level object that is available in every module. Any variable or function attached to global can be accessed from anywhere in your Node.js application.

Key Points About global

  • Always Available:
    • The global object is automatically available in all Node.js modules without needing to require or import it.
  • Namespace for Global Variables:
    • You can attach properties to global if you need truly global variables or functions. However, this is generally discouraged because it can lead to naming collisions and make your code harder to debug.
  • Example Usage:

    // Attaching a variable to the global object:
    global.myGlobalValue = 'Hello, World!';
    
    // Now, in any module, you can access it:
    console.log(global.myGlobalValue); // "Hello, World!"
    
  • Avoid Polluting the Global Namespace
    • It's best practice to limit the use of global to prevent unintended side effects across the application. Instead, consider using module-level scope or other design patterns like dependency injection.

process

The process object is a global in Node.js that provides a wealth of information about, and control over, the current Node.js process. Since it's available in every module without needing to require or import it, you can use it to interact with the environment your application runs in.

Key Properties

  • process.argv
    • An array containing the command-line arguments passed when the Node.js process was launched.

      // If you run: node app.js hello world
      console.log(process.argv);
      // Output might be: ['/usr/local/bin/node', '/path/to/app.js', 'hello', 'world']
      
  • process.env
    • An object contains the user environment. It's commonly used to access environment variables.

      console.log(process.env.NODE_ENV); // e.g., "development" or "production"
      
  • process.pid
    • The process ID of the current Node.js process.
  • process.cwd()
    • A function that return the current working directory.
  • process.version
    • A string representing the Node.js version the process is running.

Key Methods

  • process.exit([code])
    • Terminates the process with an optional exit code (default is 0).

      if (errorCondition) {
        console.error('An error occurred');
        process.exit(1); // Exit with a failure code
      }
      
  • process.on(event, callback)
    • Allows you to listen to events emitted by the process. For example, you can listen for the exit event.

      process.on('exit', (code) => {
        console.log(`Process exited with code: ${code}`);
      });
      
  • process.nextTick(callback)
    • Schedules a callback to be invoked in the next iteration of the event loop, before any I/O events.

      process.nextTick(() => {
        console.log('Executed in the next tick of the event loop');
      });
      
  • process.stdout and process.stderr
    • Writable streams that allow you to output data to the console or error stream.

      process.stdout.write('Hello from process.stdout\n');
      process.stderr.write('This is an error message\n');

Buffer

In Node.js, the Buffer is a global object used for handling raw binary data. Unlike strings, which represent text, Buffers allow you to work with binary data directly—making them essential when dealing with streams, file I/O, network communications, and more.

Common Buffer Methods

  • Creating a Buffer from a String:

    // Creates a Buffer containing the UTF-8 encoded string "Hello, world!"
    const buf = Buffer.from('Hello, world!', 'utf8');
    console.log(buf); // <Buffer 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21>
    
  • Allocate a Buffer of a Fixed Size:

    // Allocates a Buffer of 10 bytes, filled with zeros
    const buf2 = Buffer.alloc(10);
    console.log(buf2); // <Buffer 00 00 00 00 00 00 00 00 00 00>
    

__dirname and __filename

Provides the directory name and the full file path of the currently executing script, crucial for the file path resolution.

console.log(__dirname);
console.log(__filename);

require, module and export

In Node.js, every file is treated as a module, and the CommonJS module system uses three key components:

  • require:
    A function used to load and cache modules. When you call require('module-name') or require('./file'), Node.js executes that module’s code (if it hasn’t been loaded already) and returns its module.exports.
  • module:
    An object representing the current module. It has an exports property that defines what the module makes available to other modules.
  • exports:
    A shortcut to module.exports. You can add properties to exports (e.g., exports.myFunction = ...) so they become part of the exported interface. However, if you reassign exports entirely (e.g., exports = myFunction), it won’t change module.exports.

setTimeout

Schedules a callback function to run after at least a specified delay (in milliseconds).

Usage Example:

const timeoutId = setTimeout(() => {
  console.log('This runs after 2000 ms');
}, 2000);
  • Cancellation:
    • Use clearTimeout(timeoutId) to cancel the scheduled callback before it executes.

setInterval

Schedules a callback function to run repeatedly with a fixed delay between each execution.

Usage Example:

const intervalId = setInterval(() => {
  console.log('This runs every 1000 ms');
}, 1000);
  • Cancellation:
    • Use clearInterval(intervald) to stop the repeated execution.

SetImmediate

Schedules a callback function to execute immediately after the current poll phase of the Node.js event loop.

It's similar to setTimeout(fn, 0), but the ordering is more predictable for I/O operations in Node.

Usage Example:

const immediateId = setImmediate(() => {
  console.log('This runs immediately after I/O events');
});
  • Cancellation:
    • Use clearImmediate(immediateId) to cancel the scheduled immediate callback.

Use Cases:

  • Use setTimeout when you want to run something after a specific delay.
  • Use setInterval when you need repeated execution.
  • Use setImmediate when you want to queue a callback to run as soon as possible after I/O events, ensuring it runs after the current operations finish.

console

The console object is a global object in Node.js that provides a simple debugging console. It’s similar to the browser’s console object but is tailored for server-side environments. Here are some key points:

  • Output Streams:
    • console.log(), console.info(): Write to the standard output (stdout).
    • console.error(), console.warn(): Write to the standard error (stderr).
  • Methods for Debugging:
    • console.dir(): Prints a JavaScript object in a readable format (uses util.inspect under the hood).
    • console.table(): Displays tabular data as a table.
  • Timing Functions:
    • console.time(label) and console.timeEnd(label): Measure the duration of code execution.
  • Stack Traces:
    • console.trace(): Prints a stack trace to help identify where a particular code path was reached.
  • Global Availability:
    Since console is a global object, you can use it anywhere in your Node.js code without requiring any modules.

Example Usage:

console.log("Hello, world!"); // Standard output
console.error("This is an error message."); // Standard error

const obj = { name: "Alice", age: 30 };
console.dir(obj, { depth: null, colors: true }); // Pretty-print an object

console.table([
  { id: 1, task: "Write code" },
  { id: 2, task: "Test code" },
  { id: 3, task: "Deploy code" }
]);

console.time("processTime");
setTimeout(() => {
  console.timeEnd("processTime"); // Logs the time taken for setTimeout to complete
}, 1000);

function myFunction() {
  console.trace("Trace output for myFunction");
}
myFunction();