Page Content

Tutorials

What is the process Global Object in NodeJS?

Global Object in NodeJS

The WINDOW object is probably very recognisable to you from browser-based JavaScript. When JavaScript code runs in a web browser, this global object acts as the execute context. The browser window’s attributes and methods, like document, which gives access to the Document Object Model (DOM), are included, along with any global variables, functions, and objects.

The JavaScript runtime environment Node.js, on the other hand, allows JavaScript code to be executed outside of a browser. The WINDOW object is not accessible to Node.js due to this basic difference. Instead, Node.js offers a GLOBAL object, which is comparable to the browser environment’s WINDOW object. Node.js programs use this GLOBAL object as their top-level scope. As with WINDOW in a browser, for example, you may use functions like setInterval and setTimeout directly on the GLOBAL object in Node.js.

Node.js is mostly used for server-side and command-line applications, where system-level access is necessary and browser-specific features like DOM manipulation are superfluous.

The Object

A global object in Node.js, the process object gives control and information about the active Node.js process. Applications written in Node.js can always access it without explicitly importing it using require(). The process object has the ability to emit and listen for events since it is an instance of EventEmitter. It provides information about the V8 engine, which is the Node.js runtime environment, as well as helpful low-level references.

The following are some of the process object’s primary features:

Accessing Command-Line Arguments via

Any values that you enter after the script name when running a Node.js script from the command line are referred to as command-line arguments. The process.argv array contains the values for these arguments.

The process.argv array has a specific structure:

process.argv: The path of the executable that started the Node.js process (e.g., /usr/bin/node).

process.argv: The path to the JavaScript application file being executed (e.g., /home/sammy/first-program/arguments.js).

process.argv and beyond: These elements contain the actual command-line arguments provided by the user.

The actual command-line arguments supplied by the user are contained in process.argv and later items.

These arguments are available for use in modifying the behaviour of your program. For instance, the slice() method can be applied to the array, beginning at index 2, to receive only the user-supplied arguments:

// Example: arguments.js
console.log(process.argv); // Full array including node executable and script path 
// To get only user-provided arguments 
const userArgs = process.argv.slice(2);
console.log(userArgs);

If you run node arguments.js hello world:

  • The first console.log might output something like: [ '/usr/bin/node', '/path/to/arguments.js', 'hello', 'world' ].
  • The second console.log (for userArgs) would output: [ 'hello', 'world' ].

In your application, you can then use these arguments for conditional logic.

Accessing Environment Variables via

The operating system (OS) provides key-value pairs called environment variables that are kept outside of a program. Usually used for state management or configuration, they are available to all processes that are currently operating. By returning an object with all of the environment variables that were available when the Node.js process began, the env property of the process object grants access to these variables.

You can access specific environment variables by referencing their names as properties of process.env:

// Example: environment.js
console.log(process.env); // Outputs a large object with all environment variables 
// Access a specific environment variable, e.g., HOME or PATH 
console.log(process.env['HOME']);
console.log(process.env.PATH);
// Common example: NODE_ENV 
console.log(process.env.NODE_ENV); // Often 'development' by default 

You can also iterate over user-specified environment variable names from command-line arguments and print their values:

// Example: echo.js
const args = process.argv.slice(2); // Get user-provided arguments 
args.forEach(arg => {
    let envVar = process.env[arg];
    if (envVar === undefined) {
        // Use console.error for error messages, typically goes to stderr stream 
        console.error(`Could not find "${arg}" in environment`);
    } else {
        // Use console.log for standard output, typically goes to stdout stream 
        console.log(envVar);
    }
});

If you run node echo.js HOME PWD NOT_DEFINED

  • The values for PWD and HOME will be printed to standard output.
  • NOT_DEFINED” will result in a standard error message, such as Could not find "NOT_DEFINED" in environment.

Interacting with Standard Input/Output (, )

Access to the Node.js process standard input (stdin) and output (stdout) streams is also made possible by the process object.

  • The property process.stdin yields a readable stream that is comparable to or linked to standard input. You can record user input by listening for data events on this stream.
  • The property process.stdout yields a Writable stream that is comparable to or linked to standard output. Despite the fact that console.log() is frequently used for output, process.stdout.write() automatically adds a new line when writing to the standard output.

Here’s an example of reading from standard input and writing to standard output:

// Example: stdin_stdout.js
process.stdin.resume(); // Resumes the stdin stream to begin receiving data 
console.log('Enter the data to be displayed (Ctrl+D to end):');
process.stdin.on('data', function(data) {
    // Write the received data to standard output 
    process.stdout.write(data);
});
// You can pipe streams as well, for example:
// process.stdin.pipe(process.stdout); 

This script will enable you to text in your terminal and have it repeated back to the screen while you type.

The GLOBAL object is provided by Node.js for a comparable top-level scope, whereas the WINDOW object is essential to browser JavaScript. A key global tool in Node.js, the process object provides developers with fine-grained control and details about the active process, from controlling standard input and output streams to handling environment variables and command-line arguments. These attributes highlight how well Node.js works for creating reliable command-line and back-end apps.

Index