Node.js `os` Module: Accessing Operating System Information

Learn how to use Node.js's `os` module to retrieve key operating system information. This tutorial details essential methods for accessing system architecture, CPU usage, memory, network interfaces, and more, demonstrating how to leverage this information for building adaptable and informative applications.



Using the Node.js `os` Module for System Information

Introduction

Node.js's `os` module provides functions for accessing basic operating system information. This is useful for tasks like adapting your application's behavior based on the system's architecture, available memory, or other system-specific details. This article lists and explains the key methods of this module.

Key Methods of the `os` Module

Method Description
os.arch() Returns the system's CPU architecture (e.g., `x64`, `ia32`).
os.cpus() Returns an array of objects, each representing a CPU core, with details like model, speed, and usage times.
os.endianness() Returns the CPU's endianness (`'BE'` for big-endian, `'LE'` for little-endian).
os.freemem() Returns the amount of free system memory (in bytes).
os.homedir() Returns the home directory of the current user.
os.hostname() Returns the system's hostname.
os.loadavg() Returns an array of the 1, 5, and 15-minute load averages (system load).
os.networkInterfaces() Returns an object containing information about network interfaces.
os.platform() Returns the operating system platform (e.g., `'darwin'`, `'win32'`, `'linux'`).
os.release() Returns the operating system release version.
os.tmpdir() Returns the default temporary directory path.
os.totalmem() Returns the total amount of system memory (in bytes).
os.type() Returns the operating system type (e.g., `'Linux'`, `'Darwin'`, `'Windows_NT'`).
os.uptime() Returns system uptime in seconds.
os.userInfo([options]) Returns information about the current user.

Examples

Example 1: Basic System Information

Example 1

const os = require('os');
console.log("Free memory:", os.freemem());
console.log("Home directory:", os.homedir());
// ... (other methods) ...

Example 2: CPU and Network Information

Example 2

const os = require('os');
console.log("CPU information:", os.cpus());
console.log("Network interfaces:", os.networkInterfaces());

Conclusion

The Node.js `os` module provides a simple way to access system information, making it useful for tasks like system monitoring, adapting application behavior based on the environment, and providing diagnostic information.