Node.js Important Globals and Process Object

Co-Founder, @CreoWis | Teacher, @tapaScript | Founder, @ReactPlay | YouTuber | Writer | Human
Search for a command to run...

Co-Founder, @CreoWis | Teacher, @tapaScript | Founder, @ReactPlay | YouTuber | Writer | Human
No comments yet. Be the first to comment.
Traditional SSR is great, but it has a massive buffering problem. Let's look into the SSR Streaming and learn how it could be a game changer.

Learn how to build maintainable, reusable forms in React using design patterns like custom hooks, compound components, and context for scalable CRUD

Learn how JavaScript variables work, including let vs const, primitive and reference types, pass by value, and how JavaScript stores data in memory.

A beginner-friendly introduction to JavaScript covering what it is, how it works, and how to set up your JavaScript environment

Learn how the promises are handled internally using event loop. This concept is essentials to debug and work with async programming.

GreenRoots Blog - A Blog by Tapas Adhikary
186 posts
Educator | YouTuber | Building ReactPlay | Let's Connect
This is the continuation of my previous post in the Node.js series,
In the last post of the series, we learned about the global, which contains all the available functionalities by default to a node.js program without importing or requiring any modules explicitly. This post will go a bit deeper and learn about some useful globals that are important for node.js programming.
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 are used for defining what a module exports and make available for other modules to import and use. We will learn about exports in greater detail in our future posts.
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');
The process object is a global one that provides information about the current process and provides a way to control 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 a 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 we launched the Node.js process. This handy property is 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,
console.log(process.argv);
It outputs:

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.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 been completed fully, including I/O operations to process.stdout and process.stderr.
Another feature of the 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 the keyboard. Once we did with typing and pressed enter key, we will see the text is printed to the console as:

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. I hope you found it useful. Stay tuned for the next post as a continuation of the series on Node.js concepts.