Node.js “os” Module With Examples

The “os” module of Node.js plays a crucial role in providing information about the operating system and underlying hardware. In this tutorial, we’ll delve into the key functionalities of the os module and explore how it can be utilized in Node.js applications.

Introduction to the “os” Module

The os module is part of Node.js’s standard library, meaning it doesn’t require separate installation. To start using it, include the module in your script:

const os = require('os');

Now, let’s explore the major features and functions the os module offers.

1. Retrieving Operating System Information

“os.platform()”: Determining the Operating System Platform

The os.platform() method returns a string indicating the operating system platform. This is particularly useful for writing cross-platform applications.

const platform = os.platform();
console.log('Platform:', platform);

The platform variable will hold values such as ‘darwin’ (macOS), ‘win32’ (Windows), or ‘linux’ (Linux).

“os.arch()”: Determining CPU Architecture

The os.arch() method provides information about the CPU architecture. This is crucial when dealing with platform-specific code or optimizations.

const architecture = os.arch();
console.log('Architecture:', architecture);

Possible values for architecture include “x64“, “x86“, and “arm“.

2. Retrieving System Information

“os.cpus()”: Obtaining CPU Information

The os.cpus() method returns an array of objects, each containing information about a logical CPU core. This can be valuable for tasks such as load balancing or performance monitoring.

const cpus = os.cpus();
console.log('CPUs:', cpus);

Each object in the array provides details such as the CPU model, speed, and times.

“os.totalmem()” and “os.freemem()”: Monitoring Memory Usage

The os.totalmem() method returns the total amount of system memory, while os.freemem() provides information about the free system memory.

const totalMemory = os.totalmem();
const freeMemory = os.freemem();

console.log('Total Memory:', totalMemory, 'bytes');
console.log('Free Memory:', freeMemory, 'bytes');

These functions are useful for optimizing memory-intensive operations.

3. Retrieving Network Interface Information

“os.networkInterfaces()”: Exploring Network Interfaces

The os.networkInterfaces() method returns an object containing information about the system’s network interfaces. This includes details like IP addresses and MAC addresses.

const networkInterfaces = os.networkInterfaces();
console.log('Network Interfaces:', networkInterfaces);

This can be beneficial for network-related tasks and server configuration.