Crystal Studio Labs · v1.0.3

Real-Time
System Monitor
for Node.js

CPU, memory, disk, network, battery, GPU — live terminal dashboard with sparklines, threshold alerts, HTTP API, file logging, CLI binary and full TypeScript support. Zero external dependencies.

$ npm install @crystal-studio-labs/crystalsystem.js copy
v1.0.3 MIT 0 deps Node 14+ TypeScript Cross-Platform

Why crystalsystem.js

Everything you need.
Nothing you don't.

Built entirely on Node.js built-ins. No audit warnings, no dependency tree, no version conflicts — ever.

01
Real CPU %
Actual usage via CPU time-delta sampling — not just load average. Catches spikes load average misses entirely.
02📊
Sparklines
Live ▁▂▄▆█ ASCII history graphs for CPU and memory inside the terminal dashboard. Color-coded by severity.
03🔔
Alert System
Threshold alerts with configurable cooldown. Fire on CPU, memory or disk. Built-in per-type spam prevention.
04📡
Event Emitter
cs.on('data', fn) every tick. cs.on('alert', fn) on breach. cs.on('stop', fn) on teardown.
05🌐
HTTP API
Built-in JSON server. / /cpu /memory /disk /network /battery /health — all CORS enabled.
06📝
File Logging
JSON-line stats log every tick. logger.readAll() for historical analysis — find peak CPU, average RAM and more.
07🖥️
CLI Binary
crystalsystem --once --json -p 3001 -l log.json --no-gpu — full control without writing a single line of code.
08🔝
Top Processes
Shows the top N processes sorted by memory usage inside the dashboard — a lightweight inline htop.
09📘
TypeScript
Full .d.ts definitions for every function, interface, option and event. Zero @types packages required.

Usage

From zero to live monitor
in three lines.

Every example below is copy-paste ready. No config, no boilerplate, no extra packages.

const { crystalsystem } = require('@crystal-studio-labs/crystalsystem.js');

crystalsystem({
  interval:      5000,         // refresh every 5 seconds
  clearConsole:  true,
  showColors:    true,
  showNetwork:   true,
  showDisk:      true,
  showBattery:   true,
  showGPU:       true,
  showProcesses: true,
  httpPort:      3001,         // optional live JSON API
  logFile:       'stats.json', // optional file log
  thresholds: {
    cpu:    80,
    memory: 75,
    disk:   85,
  },
});
const { CrystalSystem } = require('@crystal-studio-labs/crystalsystem.js');

const cs = new CrystalSystem({
  interval:   2000,
  thresholds: { cpu: 80, memory: 75, disk: 85 },
});

// Fires every tick with a full SystemStats object
cs.on('data', (stats) => {
  console.log('CPU:',  stats.cpu.loadPercent);
  console.log('RAM:',  stats.memory.percent);
  console.log('Net↓:', stats.network.rxSpeed);
  console.log('Net↑:', stats.network.txSpeed);
});

// Fires when a threshold is breached
cs.on('alert', ({ type, message, value, threshold }) => {
  console.error(`⚠️  [${type.toUpperCase()}] ${message}`);
  // Send to Discord, Slack, Telegram, email — see Alerts section
});

cs.on('stop', () => console.log('Monitor stopped.'));

cs.start();

// Change a threshold at runtime (no restart needed)
cs.setThreshold('cpu', 70);

// One-shot snapshot without a display loop
const snap = cs.snapshot();
console.log(snap.cpu.model, snap.memory.total);

// Stop after 60 seconds
setTimeout(() => cs.stop(), 60_000);
const { crystalsystem, startHttpServer } = require('@crystal-studio-labs/crystalsystem.js');

// Start dashboard + HTTP API together
crystalsystem({ httpPort: 3001 });

// ── Available endpoints ──────────────────────────────
// GET /          → All stats as JSON
// GET /cpu       → CPU model, speed, cores, usage %
// GET /memory    → Total, used, free, percent
// GET /network   → Speeds + cumulative traffic
// GET /disk      → Partitions, total, used, free
// GET /battery   → Level, charging status
// GET /health    → { status: 'ok', uptime: ... }
// All responses include Access-Control-Allow-Origin: *

// Or start the API server independently (no dashboard)
const server = startHttpServer(4000);
// server is a Node.js http.Server — call server.close() to stop

// Fetch from anywhere
const res  = await fetch('http://localhost:3001/cpu');
const data = await res.json();
console.log(data.model, data.loadPercent);
const { crystalsystem, createLogger, getAllStats } = require('@crystal-studio-labs/crystalsystem.js');

// Auto-log every tick via the main monitor
crystalsystem({ logFile: 'stats.json', interval: 10_000 });

// ── Or log manually ──────────────────────────────────
const logger = createLogger('stats.json');

// Write a snapshot right now
logger.write(getAllStats());

// Read all saved snapshots back
const history = logger.readAll();
console.log(`${history.length} entries recorded`);

// Analyse: find peak and average CPU
const peakCPU = Math.max(...history.map(s => s.cpu.loadRaw));
const avgCPU  = history.reduce((a, s) => a + s.cpu.loadRaw, 0) / history.length;
console.log(`Peak: ${peakCPU.toFixed(2)}%  Avg: ${avgCPU.toFixed(2)}%`);
import crystalsystem, {
  CrystalSystem,
  CrystalSystemOptions,
  SystemStats,
  AlertEvent,
  CPUInfo,
  MemoryInfo,
} from '@crystal-studio-labs/crystalsystem.js';

const options: CrystalSystemOptions = {
  interval:   3000,
  thresholds: { cpu: 80, memory: 75, disk: 85 },
  httpPort:   3001,
};

const cs: CrystalSystem = crystalsystem(options);

cs.on('data', (stats: SystemStats) => {
  const cpu: CPUInfo    = stats.cpu;
  const mem: MemoryInfo = stats.memory;
  console.log(cpu.loadPercent, mem.percent);
});

cs.on('alert', (alert: AlertEvent) => {
  console.error(`[${alert.type.toUpperCase()}] ${alert.message}`);
});
# Install globally
$ npm install -g @crystal-studio-labs/crystalsystem.js

# Live dashboard (5s refresh default)
$ crystalsystem

# Custom interval
$ crystalsystem -i 2

# One-shot display then exit
$ crystalsystem --once

# JSON snapshot to stdout (pipe-friendly)
$ crystalsystem --json | jq '.cpu.loadPercent'

# Dashboard + HTTP API on port 3001 + file log
$ crystalsystem -p 3001 -l stats.json

# Hide sections you don't need
$ crystalsystem --no-disk --no-gpu --no-battery

# Pipe clean output to a file
$ crystalsystem --once --no-color > snapshot.txt

# All flags
$ crystalsystem --help

Documentation

Full API reference.

Every function, method, option and TypeScript interface documented in one place.

Installation #

Install from npm. No other packages are installed — crystalsystem.js uses only Node.js built-in modules.

# npm npm install @crystal-studio-labs/crystalsystem.js # yarn yarn add @crystal-studio-labs/crystalsystem.js # Install CLI globally npm install -g @crystal-studio-labs/crystalsystem.js

Requires Node.js 14 or higher. Works on Linux, macOS, Windows, Android (Termux) and BSD.

Functions #

All functions are available as named exports. Import only what you need.

FunctionReturnsDescription
crystalsystem(opts?)CrystalSystemStart live monitor. Returns a running instance.
buildSystemTable(opts?)stringFull ANSI dashboard as a string. No loop started.
getAllStats(opts?)SystemStatsOne-shot snapshot of all stats. No display.
startHttpServer(port?, opts?)http.ServerStart HTTP API independently without dashboard.
createLogger(path)LoggerCreate a JSON-line file logger.
getPlatformInfo()PlatformInfoOS name, arch, hostname, release.
getCPUInfo()CPUInfoModel, speed, cores, real usage % via time delta.
getMemoryInfo()MemoryInfoTotal, used, free, percentage.
getNetworkInfo()NetworkInfoCumulative traffic and live speed.
getDiskInfo()DiskInfoPartitions, total, used, free.
getBatteryInfo()BatteryInfoLevel and charging status.
getGPUInfo()GPUInfoGPU model where detectable.
getProcessInfo()ProcessInfoPID, Node version, heap usage.
getTopProcesses(n?)TopProcess[]Top N processes sorted by memory.
formatBytes(n, dec?)stringConvert bytes to readable string — "1.4 GB".
sparkline(arr, width?)stringANSI sparkline from a number array.

CrystalSystem Class #

CrystalSystem extends Node's EventEmitter. Use it when you need programmatic control — starting and stopping, listening to events, or changing thresholds at runtime.

const { CrystalSystem } = require('@crystal-studio-labs/crystalsystem.js'); const cs = new CrystalSystem(options); cs.start();
MethodReturnsDescription
.start()thisStart the monitor loop and HTTP server if configured.
.stop()thisStop loop and close HTTP server. Emits 'stop'.
.display()voidRender and print the dashboard immediately.
.snapshot()SystemStatsGet a one-shot stats object without displaying.
.setThreshold(type, n)thisUpdate a threshold at runtime. No restart needed.

Options #

Pass an options object to crystalsystem() or new CrystalSystem(). All options are optional.

OptionTypeDefaultDescription
intervalnumber5000Refresh in ms. Set to 0 to display once with no loop.
clearConsolebooleantrueClear terminal before each render.
showColorsbooleantrueEnable ANSI colors in the dashboard.
showNetworkbooleantrueShow network section.
showDiskbooleantrueShow disk section.
showBatterybooleantrueShow battery section if supported.
showGPUbooleantrueShow GPU section if detectable.
showProcessesbooleantrueShow top processes section.
historySizenumber30Number of data points kept for sparklines.
logFilestring|nullnullPath to JSON-line log file. Written every tick.
httpPortnumber|nullnullPort to start the HTTP API server on.
thresholds.cpunumber90CPU alert threshold %.
thresholds.memorynumber85Memory alert threshold %.
thresholds.disknumber90Disk alert threshold %.

Events #

All events are emitted on the CrystalSystem instance. Use cs.on(event, fn) to listen.

EventPayloadDescription
'data'SystemStatsEmitted every tick. Contains all stats in one object.
'alert'AlertEventEmitted when CPU, memory or disk exceeds threshold.
'stop'voidEmitted when .stop() is called.

The AlertEvent object has four properties: type ('cpu' | 'memory' | 'disk'), message (string), value (number — current %), threshold (number — configured limit).

TypeScript Types #

All interfaces are exported from the package. No @types package needed.

InterfaceUsed for
CrystalSystemOptionsOptions passed to crystalsystem() or new CrystalSystem()
SystemStatsFull snapshot — returned by snapshot() and 'data' event
AlertEventPayload of the 'alert' event
PlatformInfoReturn type of getPlatformInfo()
CPUInfoReturn type of getCPUInfo()
MemoryInfoReturn type of getMemoryInfo()
NetworkInfoReturn type of getNetworkInfo()
NetworkInterfaceIndividual interface entry inside NetworkInfo
DiskInfoReturn type of getDiskInfo()
PartitionInfoIndividual partition inside DiskInfo
BatteryInfoReturn type of getBatteryInfo()
GPUInfoReturn type of getGPUInfo()
ProcessInfoReturn type of getProcessInfo()
TopProcessIndividual entry in getTopProcesses()
AlertThresholdsShape of the thresholds option
LoggerReturn type of createLogger()

HTTP API #

Enable with httpPort: 3001 in options, or start independently with startHttpServer(3001). All endpoints return JSON with Access-Control-Allow-Origin: *.

RouteReturns
GET /Full SystemStats object
GET /cpuCPUInfo — model, speed, cores, usage
GET /memoryMemoryInfo — total, used, free, percent
GET /networkNetworkInfo — speeds and cumulative traffic
GET /diskDiskInfo — partitions, total, used, free
GET /batteryBatteryInfo — level and charging status
GET /health{ status: 'ok', uptime: number }

CLI Flags #

All flags are available when running crystalsystem from the terminal after a global install.

FlagShortDescription
--help-hShow help and exit
--once-oDisplay once and exit (no loop)
--json-jPrint JSON snapshot to stdout and exit
--interval <sec>-iRefresh every N seconds (default: 5)
--port <port>-pStart HTTP API server on this port
--log <file>-lAppend stats to a JSON log file each tick
--no-colorDisable ANSI colors (good for piping)
--no-networkHide network section
--no-diskHide disk section
--no-batteryHide battery section
--no-gpuHide GPU section
--no-processesHide top processes section
--no-clearDon't clear console between updates

Alert Integrations

12 ways to get notified.
Zero extra packages.

Every alert type is a standalone file in the examples repository. Find them at crystalsystem.js-examples.

Platform Support

Runs everywhere
Node.js runs.

On Android/Termux, crystalsystem.js falls back to /proc/cpuinfo when os.cpus() is restricted — CPU info still works correctly.

🐧
Linux
CPUMemoryDiskNetworkBatteryGPU
🤖
Android/Termux
CPUMemoryDiskNetworkBatteryGPU
🍎
macOS
CPUMemoryDiskNetworkBatteryGPU
🪟
Windows
CPUMemoryDiskNetworkBatteryGPU
😈
FreeBSD
CPUMemoryDiskNetworkBatteryGPU