typescriptbeginner

System Information with OS Module

Retrieve system information including CPU, memory, network interfaces, and platform details using os module.

typescript
import os from 'os';

function getSystemInfo() {
  return {
    platform: os.platform(),
    arch: os.arch(),
    hostname: os.hostname(),
    release: os.release(),
    uptime: `${(os.uptime() / 3600).toFixed(1)} hours`,
    nodeVersion: process.version,
    memory: {
      total: `${(os.totalmem() / 1e9).toFixed(1)} GB`,
      free: `${(os.freemem() / 1e9).toFixed(1)} GB`,
      usage: `${((1 - os.freemem() / os.totalmem()) * 100).toFixed(1)}%`,
    },
    cpus: {
      model: os.cpus()[0]?.model,
      cores: os.cpus().length,
      speed: `${os.cpus()[0]?.speed} MHz`,
    },
    network: Object.entries(os.networkInterfaces())
      .flatMap(([name, addrs]) =>
        (addrs ?? []).filter(a => !a.internal).map(a => ({
          interface: name,
          address: a.address,
          family: a.family,
        }))
      ),
    loadAverage: os.loadavg().map(l => l.toFixed(2)),
    tmpdir: os.tmpdir(),
    homedir: os.homedir(),
  };
}

function printTable(obj: Record<string, any>, indent = 0) {
  for (const [key, val] of Object.entries(obj)) {
    const pad = ' '.repeat(indent);
    if (typeof val === 'object' && !Array.isArray(val)) {
      console.log(`${pad}${key}:`);
      printTable(val, indent + 2);
    } else {
      console.log(`${pad}${key}: ${JSON.stringify(val)}`);
    }
  }
}

printTable(getSystemInfo());

Use Cases

  • Server health dashboards
  • System monitoring scripts
  • Environment diagnostics

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.