node-cpu-watchdog
v1.0.2
Published
A TypeScript-compliant CPU usage watchdog for Node.js applications.
Downloads
60
Maintainers
Readme
node-cpu-watchdog
A production-ready, type-safe CPU watchdog for Node.js applications. Supports both Monitor-Only Mode and Automatic Graceful Server Restart Mode. Works with Express, Fastify, NestJS, HTTP/HTTPS, custom servers, PM2, Docker, and Kubernetes.
Operating Modes
- Monitor-Only Mode (
autoRestart: false): Continuously monitors CPU usage across cores, logs real-time utilization, and triggers callbacks without stopping your server or exiting the process. - Auto-Restart Mode (
autoRestart: true): Gracefully closes your HTTP/Express/Fastify/NestJS server when sustained CPU overload is detected, touching entry files for Nodemon dev reloads or triggering PM2/Docker/Kubernetes process restarts.
Installation
npm install node-cpu-watchdogUsage Examples
1. Monitor-Only Mode (No Process Restart)
TypeScript
import { CpuMonitor } from "node-cpu-watchdog";
const cpuMonitor = new CpuMonitor({
threshold: 80, // Check if CPU exceeds 80%
intervalMs: 3000, // Measure every 3 seconds
autoRestart: false, // Monitor-only mode (do NOT restart process/server)
});
// Start monitoring
cpuMonitor.start();JavaScript
const { CpuMonitor } = require("node-cpu-watchdog");
const cpuMonitor = new CpuMonitor({
threshold: 80,
intervalMs: 3000,
autoRestart: false,
});
cpuMonitor.start();2. Graceful Auto-Restart Mode (Express Example)
TypeScript (server.ts)
import express from "express";
import { CpuMonitor } from "node-cpu-watchdog";
const app = express();
const server = app.listen(3000, () => {
console.log("Server running on port 3000");
});
const cpuMonitor = new CpuMonitor({
threshold: 70, // 70% CPU threshold
intervalMs: 3000, // Check every 3 seconds
maxSustainedBreaches: 3, // 3 consecutive breaches trigger restart
autoRestart: true, // Auto-restart mode (default)
server, // Gracefully close Express server before restart
});
cpuMonitor.start();JavaScript (server.js)
const express = require("express");
const { CpuMonitor } = require("node-cpu-watchdog");
const app = express();
const server = app.listen(3000);
const cpuMonitor = new CpuMonitor({
threshold: 70,
intervalMs: 3000,
maxSustainedBreaches: 3,
autoRestart: true,
server,
});
cpuMonitor.start();3. Fastify Framework (Auto-Restart)
import Fastify from "fastify";
import { CpuMonitor } from "node-cpu-watchdog";
const fastify = Fastify();
fastify.listen({ port: 3000 }).then(() => {
const cpuMonitor = new CpuMonitor({
threshold: 75,
intervalMs: 3000,
maxSustainedBreaches: 3,
autoRestart: true,
server: fastify,
});
cpuMonitor.start();
});4. NestJS Framework (Auto-Restart)
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { CpuMonitor } from "node-cpu-watchdog";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
const cpuMonitor = new CpuMonitor({
threshold: 75,
intervalMs: 3000,
maxSustainedBreaches: 3,
autoRestart: true,
server: app,
});
cpuMonitor.start();
}
bootstrap();5. Custom Threshold Callback Handler
import { CpuMonitor } from "node-cpu-watchdog";
const cpuMonitor = new CpuMonitor({
threshold: 85,
intervalMs: 2000,
maxSustainedBreaches: 2,
});
cpuMonitor.start((cpuUsage) => {
console.warn(`[Alert] CPU usage hit ${cpuUsage}%. Sending telemetry notification...`);
});Process Orchestrators (PM2, Docker, Kubernetes)
In Auto-Restart Mode, CpuMonitor closes open sockets gracefully and touches the entry file (process.argv[1]) for Nodemon, or exits with code 1 to trigger container/process managers:
- Nodemon: Automatically detects the entry file timestamp touch and restarts without crashing.
- PM2:
pm2 start dist/server.jsautomatically restarts the process on exit code1. - Docker: Set
restart: unless-stoppedorrestart: alwaysindocker-compose.yml. - Kubernetes: Default pod
restartPolicy: Alwaysprovisions a fresh container automatically.
Options API Reference
new CpuMonitor(options?: CpuMonitorOptions)
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| threshold | number | 70 | CPU threshold percentage (0-100) to trigger breach detection. |
| intervalMs | number | 3000 | Frequency in milliseconds between CPU checks. |
| maxSustainedBreaches | number | 3 | Number of consecutive breaches required before action. |
| autoRestart | boolean | true | true for graceful server restart; false for monitor-only mode. |
| server | ClosableServer | null | Express, Fastify, NestJS, HTTP/HTTPS, or Custom server instance. |
| shutdownTimeoutMs | number | 5000 | Timeout in ms for graceful shutdown before forcing exit. |
| touchFilePath | string | process.argv[1] | File path to touch (fs.utimesSync) for Nodemon auto-reloads. |
| exitCode | number | 1 | Exit code passed to process.exit(). |
Development & Build Commands
# Type check TypeScript files
npm run type-check
# Build ESM & CommonJS outputs + TypeScript types
npm run build
# Watch mode for active development
npm run devRepository
- GitHub: https://github.com/sunil380875/node-cpu-watchdog
- Issues: https://github.com/sunil380875/node-cpu-watchdog/issues
License
MIT © Sunil Kumar Mishra
