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.
Press + to interact
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