Processes
Although Node abstracts a lot of things from the operating system, you are still running in an operating system and may want to interact more directly with it. Node allows you to interact with system processes that already exist, as well as create new child processes to do work of various kinds. Although Node itself is generally a “fat” thread with a single event loop, you are free to start other processes (threads) to do work outside of the event loop.
process Module
The process module enables you to get information about and change the
settings of the current Node process. Unlike most modules, the process module is global and is always
available as the variable process.
process events
process
is an instance of EventEmitter,
so it provides events based on systems calls to the Node
process. The exit event provides a final hook before the Node process exits (see
Example 5-14). Importantly, the event loop will
not run after the exit event, so
only code without callbacks will be executed.
Example 5-14. Calling code when Node is exiting
process.on('exit', function () {
setTimeout(function () {
console.log('This will not run');
}, 100);
console.log('Bye.');
});Because the loop isn’t going to run again,
the setTimeout() code will never be
evaluated.
An extremely useful event provided by process
is uncaughtException (Example 5-15). After you’ve spent any time with Node, you’ll find that exceptions that hit the main event loop will kill your Node process. In many use cases, especially ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access