Accessing System-Level Information with Node.js `os` Module
Node.js provides the os module to interact with the underlying operating system. With the os module, you can access important system-level information such as CPU architecture, available memory, system uptime, and more.
Importing the os Module
First, require the os module in your Node.js application:
const os = require("os");Getting System Information
The os module provides several methods to retrieve key system information.
1. Getting the Operating System’s Platform
Use os.platform() to get the platform of the operating system (e.g., ‘linux’, ‘win32’, ‘darwin’):
const os = require("os");
const platform = os.platform();console.log(platform); // Output: 'linux', 'win32', or 'darwin'2. Getting the System’s CPU Architecture
Use os.arch() to get the CPU architecture (e.g., ‘x64’, ‘arm’):
const os = require("os");
const cpuArch = os.arch();console.log(cpuArch); // Output: 'x64' or 'arm'3. Getting System Uptime
Use os.uptime() to get the system’s uptime in seconds:
const os = require("os");
const uptime = os.uptime();console.log(`System Uptime: ${uptime} seconds`);4. Getting Total and Free Memory
os.totalmem(): Returns the total system memory in bytes.os.freemem(): Returns the available (free) system memory in bytes.
Example:
const os = require("os");
const totalMemory = os.totalmem();const freeMemory = os.freemem();
console.log(`Total Memory: ${totalMemory} bytes`);console.log(`Free Memory: ${freeMemory} bytes`);5. Getting CPU Information
Use os.cpus() to get information about each CPU/core, including model, speed, and times:
const os = require("os");
const cpuInfo = os.cpus();console.log(cpuInfo);This will return an array of objects with details about each CPU core, such as model, speed, and times.
6. Getting Network Interfaces
Use os.networkInterfaces() to get details about network interfaces (e.g., IPv4 and IPv6 addresses):
const os = require("os");
const networkInterfaces = os.networkInterfaces();console.log(networkInterfaces);This will return an object with network interface names as keys and interface details (including IP addresses) as values.
Conclusion
- The
osmodule in Node.js provides an easy way to access system-level information. - You can retrieve details such as the operating system platform, CPU architecture, memory usage, uptime, CPU information, and network interfaces.
- This information can be useful for system monitoring, diagnostics, or tailoring the behavior of your application based on the system’s characteristics.
For more advanced system interactions, you can combine the os module with other Node.js modules like fs for file system access and process for managing application processes.