Node.js - Processes & OS
Tags: javascript, node, eventdriven
Published: 2020-12-25 02:54:26

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/aikxjcdxek5ots28sj50.jpeg)
#### Overview
This article is **Part 7** of the series [Working With NodeJS](https://dev.to/meddy672/series/20844), 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](https://nodejs.org/dist/latest-v14.x/docs/api/process.html#process_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](https://nodejs.org/dist/latest-v14.x/docs/api/os.html#os_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`.
```javascript
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.');
```
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](https://github.com/nodejs/node-v0.x-archive/issues/8863#issuecomment-66796997). 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](https://pm2.keymetrics.io/) and [forever](https://www.npmjs.com/package/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
```
##### index.js
```javascript
'use strict';
console.log('initialized');
process.stdin.pipe(process.stdout);
```
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
```javascript
'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());
```
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](https://nodejs.org/dist/latest-v14.x/docs/api/os.html#os_os) module provides functions  to retrieve information from operating system and the currently running program.
```javascript
'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());
```
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](https://nodejs.org/dist/latest-v12.x/docs/api/os.html#os_os) 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.