0
0
Node.jsframework~5 mins

os module for system information in Node.js

Choose your learning style9 modes available
Introduction

The os module helps you get details about the computer your program is running on. It tells you things like the computer's name, memory, and CPU info.

You want to show the computer's name or user info in your app.
You need to check how much free memory is available before running a big task.
You want to find out the number of CPU cores to optimize your program.
You want to log system info for debugging or support.
You want to detect the operating system type to run OS-specific code.
Syntax
Node.js
import os from 'os';

// Get system info
const hostname = os.hostname();
const platform = os.platform();
const freeMem = os.freemem();
const totalMem = os.totalmem();
const cpus = os.cpus();

Use import os from 'os' in Node.js 20+ with ES modules.

Each function returns info about the system, like hostname() returns the computer's name.

Examples
Prints the computer's network name.
Node.js
import os from 'os';
console.log(os.hostname());
Shows the operating system platform like 'win32', 'linux', or 'darwin'.
Node.js
import os from 'os';
console.log(os.platform());
Prints the amount of free memory in bytes.
Node.js
import os from 'os';
console.log(os.freemem());
Shows how many CPU cores the system has.
Node.js
import os from 'os';
console.log(os.cpus().length);
Sample Program

This program prints basic system info: the computer's name, OS platform, total and free memory in megabytes, and the number of CPU cores.

Node.js
import os from 'os';

console.log('System Information:');
console.log(`Hostname: ${os.hostname()}`);
console.log(`Platform: ${os.platform()}`);
console.log(`Total Memory: ${(os.totalmem() / 1024 / 1024).toFixed(2)} MB`);
console.log(`Free Memory: ${(os.freemem() / 1024 / 1024).toFixed(2)} MB`);
console.log(`CPU Cores: ${os.cpus().length}`);
OutputSuccess
Important Notes

Memory values are in bytes, so convert to MB or GB for easier reading.

CPU info includes details like model and speed, but here we just count cores.

Output will vary depending on the actual computer running the code.

Summary

The os module gives you easy access to system details.

Use it to get info like hostname, platform, memory, and CPU cores.

This helps your program adapt or report useful system info.