DEV Community

loading...

Node.js - Processes & OS

Matt Eddy
Software Engineer and owner of Creativethoughtz
・4 min read

Alt Text

Overview

This article is Part 7 of the series Working With NodeJS, a series of article to help simplify working with Node.js. In this article I will cover the Processes and OS Module.

Introduction

A Node.js process is the program that is currently running our code. We can control and gather information about a process using the global process object. The operating system is the host system on which a process runs and we can find information about the operating system using the core os module.

Processes

A process object is a global object that provides information about, and control over, the current Node.js process. The process object is an instance of the EventEmitter and therefore able to register events. Two of the commonly used events are beforeExit and exit.

process.once('beforeExit', (code) => {
  setTimeout(() => { console.log('Do some work') }, 200);
  console.log('Process beforeExit event with code: ', code);
});

process.on('exit', (code) => {
  console.log('Process exit event with code: ', code);
});

console.log('This message is displayed first.');
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, we register the beforeExit and exit events. The beforeExit event is emitted when Node.js empties the event loop and has no additional work to schedule. Notice the beforeExit event is registered using the once method. We use the once method because asynchronous operations are possible within this method. If we changed the event to use the on method the process would enter into an infinite loop because the setTimeout will be placed back into the event loop before exiting. Try it out. Now, within the exit event only synchronous operations are allowed. When the exit event is emitted any additional work scheduled for the event loop will be abandoned. Another commonly used method is uncaughtException. This method is used for exceptions that were not accounted for within the application and may cause the process to crash. However, you should avoid using this method as it is know to lead to an unexpected and dangerous state in your application. To handle unaccounted exceptions you should have an effective restart policy in place using tools like PM2 and forever.

STDIO

Three properties commonly used with the process object are stdin, stdout, and stderr. These properties provide the ability to interact with the terminal input an output also know as stdio. The stdin is a readable stream which means it behaves as an input. Both stdout and stderr are writable streams meaning they act as outputs. The one common method all streams implement is the pipe method. Lets see an example. I'll provide some input to the process.stdin via the terminal using Node.js crypto module. I'll then log that input to the console from another file called index.js using the pipe method.

terminal
node -p "crypto.randomBytes(10).toString('hex')" | node index.js
Enter fullscreen mode Exit fullscreen mode
index.js
'use strict';
console.log('initialized');
process.stdin.pipe(process.stdout);
Enter fullscreen mode Exit fullscreen mode

Running the code snippet above, outputs initialized and the random bytes generated by the crypto.randomBytes method.

As stated before, the process object contains information about the process, lets see a few examples

'use strict'
console.log('Current Directory', process.cwd());
console.log('Process Platform', process.platform);
console.log('Process ID', process.pid);
console.log('Process CPU usage', process.cpuUsage());
console.log('Process', process.memoryUsage());
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, The current working directory is whatever folder the process was executed in. The process.platform indicates the host operating system. The process.pid returns the id of the current process. The process.cpuUsage() returns the user and system CPU time usage of the current process. The process.memoryUsage() returns an object describing the memory usage of the Node.js process measured in bytes.

OS Module

The os module provides functions to retrieve information from operating system and the currently running program.

'use strict'
const os = require('os');

console.log('Hostname', os.hostname());
console.log('Home dir', os.homedir());
console.log('Temp dir', os.tmpdir());
console.log('type', os.type());
Enter fullscreen mode Exit fullscreen mode

In the above code snippet the os.hostname will return the host name of the operating system as string. The os.homedir returns the string path of the current user's home directory. The os.tmpdir returns the operating system's default directory for temporary files as a string. The os.type returns the operating system name as returned by uname. To see a complete list of available methods visit the Official Node.js Documentation for the os module.

Thank you for taking time to read this article. If you found it helpful please subscribe to the series and take care.

Discussion (0)