Node.js Important Globals and Process Object

This is the continuation of my previous post in Node.js series,

In the last post of the series, we learned about the global which contains all the functionalities that are available by default to a node.js program without importing or requiring any modules explicitly. In this post, we will go bit more deeper and learn about some useful globals that are important for node.js programming.

Global Objects

The followings are available by default in all modules.

  • __dirname

    The directory name of the current module.

    console.log(__dirname); // Note: 2 underscores as prefix.
    // The above line prints the full path to the directory of the current module.
    
  • __filename

    The file name of the current module.

    console.log(__filename); // Note: 2 underscores as prefix.
    // The above line prints the current module file's absolute path 
    // with symlinks resolved.
    
  • exports

    exports or module.exports is used for defining what a module exports and makes available for other modules to import and use. We will learn about exports in greater details in our future post.

  • require()

    It is used to import the module(non-global) and make use of what has been exported from that module. require takes an id as an argument which is usually a module name or path. It follows the CommonJS Module Pattern. We will dive in more into require() along with exports in the upcoming post. Few examples of require():

    const path = require("path");
    const v8 = require("v8");
    const { sum, sub, mul } = require('./calcModule');
    

Process Object

The process object is a global that provides information about current process, and provides way to have control over it. As it is a global, we will not need the require(id) to use it.

There are plenty of useful methods and event listeners as part of Process object.

  • process.pid

    Get Current Process id.

    console.log(process.pid);
    // the pid property returns the current process id
    

    Output: 25668 (for you it will be something else)

  • process.version

    Get node.js version at the run time.

    console.log(process.version);
    

    Output: v12.7.0

  • process.argv

    Pass command line arguments when the Node.js process was launched. This is an extremely useful property to pass command line arguments where you might want to pass configurations like memory limit, default values etc when a process is launched.

    process.argv returns an array of the arguments passed to it. By default there will be two elements in this array,

    • The first element will be the path to the node.js executable
    • The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command line arguments.
    console.log(process.argv);
    

    It outputs: process_argv.png

    Example of passing command line arguments:

    // We are printing all the arguments passed
    process.argv.forEach((val, index) => {
      console.log(`${index}: ${val}`);
    });
    

    Now, run it like:

    node src/global/global.js firstValue memory=512 last
    

    Output: process_argv2.png

  • process.exit()

    The process.exit() method instructs Node.js to terminate the process synchronously. Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr.

Standard Input and Output

Another feature of Process object is Standard Input and Output.

  • process.stdin

    The stdin property of the process object is a Readable Stream. It listens for the user input. We can wire up a listener using process.stdin and use the on function to listen for the event.

    process.stdin.on('data', data => {
      console.log(`You typed ${data.toString()}`);
      process.exit();
    });
    

    When we run the above code, we will get a prompt to enter any texts using keyboard. Once we done with typing and pressed enter key, we will see the text is printed to the console as:

    stdin.png

  • process.stdout

    The stdout property of the process object is a Writable Stream and it implements a write() method. We can use this property to send data out of our program.

    process.stdout.write('GreenRoots Blog\n');
    

    It will just write the text 'GreenRoots Blog' and a new line character into the console. Can you guess, what would be the implementation of console.log()? I know, you guessed it already!

Learn more about the Process object from here. Hope you found it useful. Stay tuned for the next post as a continuation of the series on Node.js concepts.

No Comments Yet