Process
Understand how the process object works in Node.js.
We'll cover the following
The process
object
The process
object is a global that allows us to control the current process. It also has methods that can provide useful information about the process. Being an instance of the EventEmitter
class, it has a few important events that we should know about. Let’s take a look at them.
console.log('This is the first message');process.on('beforeExit', (code) => {console.log('Process beforeExit event with code:', code);});process.on('exit', (code) => {setTimeout(() => { console.log('This will not work.') }, 0);console.log('Process exit event with code:', code);});console.log('This is the second message');// process.exit()
exit
and beforeExit
These two events can be very useful at times. Consider the scenario:
- You wish to save your program progress to the cloud once it is done processing. The
beforeExit
event is perfect for this job. It is when the event loop is empty, which means that Node.js has done all its work and is about to exit. You can register thefired emitted beforeExit
event to make a network call to your cloud drive and upload your data. - Once your data has been uploaded, you want the program to notify you with an output on the console. The
exit
event is fired whenprocess.exit()
is called, or the event loop has no additional work to perform. Theexit
event executes synchronously, and asynchronous calls may not return properly. This is why theconsole.log()
on line 8 does not work.
An important thing to note is that if we explicitly call process.exit()
, the beforeExit
event is not fired. Uncomment the code on line 14 to see what happens.
uncaughtException
Another important event to know about is the uncaughtException
. As the name suggests, this event is fired when an exception occurs that has not been handled or dealt with in the program. By default, Node.js exits and prints the stack trace in case an uncaughtException
arises. Using the process
object, we can cater to these exceptions and deal with them as we wish. Let’s see how it works.
// process.on('uncaughtException', (err, origin) => {// console.error('This caused a problem:', origin);// console.error(err.stack);// });setTimeout(() => {console.log('This will also work');}, 1000);console.log('This will work');thisDoesNotExist();console.log('This will not work');
Run the code and see what output you get. You will notice that the console.log()
in setTimeout()
does not get printed. In case of an uncaughtException
, Node.js exits. However, if we uncomment the code block from line 1 to line 4 and rerun the code, our setTimeout()
will work as expected.
It should be noted that attempting to resume the process after an exception arises is never advised, as it may cause more significant problems later on.
Some methods
Let’s take a look at a few common methods that the process
object provides.
Methods | Explanation |
---|---|
process.argv |
Returns an array containing the command line arguments |
process.cwd() |
Returns the current working directory of the Node.js process. |
process.chdir(directory) |
Changes the current working directory of the Node.js process |
process.exit([code]) |
Instructs Node.js to terminate the process synchronously with an exit status of code; the default is 0 |
Streams
As we know that process.stdin
, process.stdout
, and process.stderr
all are streams.
A stream is an abstract interface for working with streaming data in Node.js. Streams can be readable, writable, or both. All streams are instances of EventEmitter
. With that out of the way, let’s look at the streams.
process.stdin
is a readable stream. We use it to read data from user input.process.stdout
is a writable stream. It is written to asynchronously, making it non-blocking.console.log
andconsole.info
use this stream.process.stderr
is also a writable stream. It is written to synchronously and, hence, is blocking.console.warn
andconsole.error
use this stream.
Using the process
module
The process
module is very versatile and powerful and can make the difference between a good and an amazing application. While we have discussed a few important ones, the process
module has a lot of methods that enable us to take control of our application at a much lower level. From catching exceptions to monitoring CPU usage, the process
module can do a lot. You can read up on more methods in the official documentation.
Get hands-on with 1300+ tech skills courses.