iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

os

node:os module: platform, cpus, memory, network interfaces, tmpdir. Cross-platform system info without spawning a process.

Node — node:os

EXAMPLE
import os from 'node:os';

// ===== Platform info =====
os.platform();        // 'darwin' | 'linux' | 'win32' | ...
os.type();             // 'Darwin' | 'Linux' | 'Windows_NT'
os.release();          // OS version string
os.arch();             // 'x64' | 'arm64' | ...
os.endianness();       // 'BE' | 'LE'
os.version();          // detailed kernel version

// ===== CPU =====
os.cpus();             // array of CPU info objects
os.cpus().length;      // number of cores
os.loadavg();          // [1m, 5m, 15m] load averages (Linux/macOS); zeros on Windows
os.uptime();           // seconds since boot

// ===== Memory =====
os.totalmem();         // bytes
os.freemem();          // bytes free RAM

// Convert:
const gb = (b) => (b / 1024 ** 3).toFixed(2);
console.log(\`free ${gb(os.freemem())} GB / ${gb(os.totalmem())} GB\`);

// ===== Filesystem =====
os.tmpdir();           // '/tmp' or '/var/folders/...' or 'C:\Users\You\AppData\Local\Temp'
os.homedir();          // user home directory
os.hostname();
os.userInfo();         // { username, uid, gid, shell, homedir }

// ===== Network =====
os.networkInterfaces();
// Object keyed by interface name; arrays of { address, family, mac, internal, cidr }

const ip = Object.values(os.networkInterfaces())
  .flat()
  .find(i => i.family === 'IPv4' && !i.internal)?.address;
console.log('local IPv4:', ip);

// ===== End-of-line + path separator =====
os.EOL;                // '\n' on POSIX, '\r\n' on Windows
// Note: path.sep, not os.sep; os does not export the path separator.

// ===== Cross-platform tips =====
import path from 'node:path';
const tmpFile = path.join(os.tmpdir(), 'my-app-' + Date.now());

// ===== Patterns to internalise =====
// - os.tmpdir() for cross-platform temp files
// - os.cpus().length to size worker pools
// - os.EOL when emitting platform-native line endings
// - os.networkInterfaces() to find non-internal IPs

// ===== Pitfalls =====
// - os.loadavg() is zeros on Windows; do not rely on it cross-platform
// - os.freemem() does not reflect macOS 'wired vs free' semantics accurately
// - os.userInfo() may throw if no user info is available (e.g. minimal containers)
// - os.cpus() is slow on some systems; cache the result

Why it matters

node:os gives you platform info without spawning a process. Use it for temp paths, sizing worker pools, EOL handling, and IP discovery. Cross-platform metrics belong here; platform-specific shell-outs are still cleaner via child_process.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
import os from 'node:os';
console.log(os.platform(), os.cpus().length, os.totalmem());
Try it Yourself »

Discussion

Loading…