Node.js Important Globals and Process Object
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.
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 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');
Process Object
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,- 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:
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
andprocess.stderr
.
Standard Input and Output
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 theon
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.