The practical use cases of the OS module in Node.js

Mirza Leka
5 min readMay 18, 2024

Load balancing, OS-specific commands, dynamic data, constants. Meet the OS, one of the core Node.js modules that reads system information. This article will explore the use cases of the module.

In this blog, I’ll use the Node.js CLI to execute commands in the terminal. To get started, open up a Command Prompt, type node, then import the OS module into your CLI:

Retrieve User Information

The OS module fully overviews the machine that Node.js is running on. You can read the system information using a few commands:

  • Username
> os.userInfo().username
'<Your-User>'
  • Operating system
> os.platform()
'win32' (Windows)
('Darwin' if you're on Mac)
  • Home directory
> os.homedir()
'C:\\Users\\<Your-User>' (Windows)
  • Temporary files directory
> os.tmpdir()
'C:\\Users\\<Your-User>~1\\AppData\\Local\\Temp' (Windows)
  • Network information (IPv4, IPv6 & MAC address)
> os.networkInterfaces()

'Wi-Fi': [
{
address: '...',
netmask: '...',
family: 'IPv6',
mac: '...',
internal: false,
cidr: '...',
scopeid: 0
},
{
address: '...',
netmask: '...',
family: 'IPv4',
mac: ...',
internal: false,
cidr: '...'
}
],
  • CPU cores
> os.cpus()

[
{
model: 'AMD Ryzen 7',
speed: 3194,
times: {
user: 5024140,
nice: 0,
sys: 6091046,
idle: 71488406,
irq: 1413031
}
},
{
model: 'AMD Ryzen 7',
speed: 3194,
times: {
user: 3925781,
nice: 0,
sys: 2675406,
idle: 76002218,
irq: 388109
}
},
...
];

Load Balancing

As you’ve seen, the command os.cpus() retrieves information on available CPU cores, but what you’re interested in is the length of this array:

> os.cpus().length
16 // total number of CPU cores on my machine

Using the Cluster module (another native module), you can scale out your Node.js app from one up to a total number of CPU instances.

Basic server setup:

// server.js
const express = require('express'); // NPM module
const app = express();
const { PORT = 3000 } = process.env;

app.get('/', (req, res) => {
res.send('Hello World!');
});

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

By default, the Node.js app runs on a single CPU instance. With the combination of Cluster and the OS module, you can tip the scale in your favor.

Cluster (Load balancer):

// cluster.js
const cluster = require('cluster');

if (cluster.isMaster) {
const cpuCount = require('os').cpus().length; // e.g. 16

// spawn new process for each CPU core
for (let i = 0; i < cpuCount; i += 1) {
cluster.fork();
}

// spawn new cluster every time one fails
cluster.on('exit', function () {
cluster.fork();
});

} else {
// run another instance of server.js
require('./server');
}

The result is a Node.js app distributed across multiple OS cores:

> node cluster.js

Server started on port 3000
Server started on port 3000
Server started on port 3000
Server started on port 3000
Server started on port 3000
Server started on port 3000
Server started on port 3000

This can also be achieved using a process manager like PM2. More on that in my blog below:

Performance Tracking

Besides reading the static values, the OS module can also track the available RAM and CPU uptime.

  • Total memory
> os.totalmem()
16483872768 // 16GB
  • Free memory (at the time of executing the command)
> os.freemem()
7696563712
  • Uptime
> os.uptime()
80441.89 // seconds
  • Additionally, the Process module (Global built-in module) retrieves the heap, CPU, and memory usage of the running Node.js process:
> process.memoryUsage()
{
rss: 36913152,
heapTotal: 8060928,
heapUsed: 6101880,
external: 1086839,
arrayBuffers: 336264
}

> process.cpuUsage()
{ user: 609000, system: 546000 }
  • Among other things, the version and release data, of the currently running Node.js process (app), environment variables, etc:
> process.version
'v18.18.0'

> process.release
{
name: 'node',
lts: 'Hydrogen',
sourceUrl: 'https://nodejs.org/download/release/v18.18.0/node-v18.18.0.tar.gz',
headersUrl: 'https://nodejs.org/download/release/v18.18.0/node-v18.18.0-headers.tar.gz',
libUrl: 'https://nodejs.org/download/release/v18.18.0/win-x64/node.lib'
}

> process.env
... enviroment variables

Execute OS-Specific Commands

If you’re building a desktop application using tools like Electron, you’ll likely be interested in collecting as much information from the consumer.

Execute shell commands:

import shell from 'shelljs'; // NPM module that executes shell commands
import { platform } from 'os';

function createENVFile() {

const isWindows = platform().includes('win');

if (isWindows) {
shell.exec('cd. > .env');
} else {
shell.exec('touch .env');
}

}

Set behavior of desktop applications:

// From Electron.js

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});

Additionally, you can target or track supported operating system architecture versions:

> os.arch()
'x64'

> os.version()
'Windows 10 Pro'

> os.release()
'10.0.x'

> os.type()
'Windows_NT'

> os.machine()
'x86_64'

An example of that would be to limit apps to specific OS versions:

const os = require('os');

const clientVersion = 7;
const appVersion = parseInt(os.release()); // e.g. 10

if (clientVersion < appVersion) {
console.error('App supports versions 10 and above. Please upgrade.');
}

Peek into System Constants

The OS module also lets you read the Operating System Constants:

> os.constants

E2BIG: 7,
EACCES: 13,
EADDRINUSE: 100,
EAGAIN: 11,
EALREADY: 103,
ECONNREFUSED: 107,
signals: [Object: null prototype] {
SIGHUP: 1,
SIGINT: 2,
SIGQUIT: 3,
SIGILL: 4,
},
priority: [Object: null prototype] {
PRIORITY_LOW: 19,
PRIORITY_BELOW_NORMAL: 10,
PRIORITY_NORMAL: 0,
}
...

The object provides a collection of commonly used operating system-specific constants, such as

  • Signals,
  • Priority levels,
  • Dlopen Constants (Linux),
  • Windows-specific constants,
  • POSIX constants, etc.

These provide a standardized and reliable mechanism for accessing Operating System-specific features, behaviors, and configurations.
Here is a full list of constants delivered by the OS module.

Beyond OS

If the core module does not meet your expectations, these NPM modules extend its abilities:

Wrapping Up

The OS module provides an interface for accessing various system-related information and performing system-level operations. If you’d like to learn more about Node.js, be sure to check out the related articles below:

Node.js Starter

7 stories

Express.js Starter (Express-APIvantage)

4 stories

Bye for now 👋

--

--

Mirza Leka

Web Developer. DevOps Enthusiast. I share my experience with the rest of the world. Follow me on https://twitter.com/mirzaleka for news & updates #FreePalestine