A comprehensive Node.js memory management and monitoring library with real-time tracking capabilities.
npm install memvigilA comprehensive Node.js memory management and monitoring library with real-time tracking capabilities.
- Installation
- Features
- Quick Start
- Usage Examples
- TypeScript Support
- API Reference
- Production Best Practices
- License
``bash`
npm install memvigil
- ð Real-time memory monitoring
- ð CPU usage tracking
- ðĻ Automatic leak detection with severity levels
- ðļ Heap snapshot generation
- âŧïļ Garbage collection analysis
- ð Performance metrics
- ðŊ Custom threshold alerts (warning & critical)
- ð Memory trend analysis with predictions
- â ïļ Memory pressure detection
- ð Export reports (JSON/CSV)
- ð Comprehensive statistics
- ðŧ Full TypeScript support
`javascript
const MemoryMonitor = require("memvigil");
// Initialize with 200MB threshold
const monitor = new MemoryMonitor(200 1024 1024);
// Set up basic event listeners
monitor.on("thresholdExceeded", (memoryUsage) => {
console.log(
"Memory threshold exceeded:",
${(memoryUsage.heapUsed / 1024 / 1024).toFixed(2)}MB
);
});
monitor.on("leakDetected", (details) => {
console.log("Memory leak detected:", details.message);
console.log("Suggestions:", details.suggestions);
});
// Start monitoring with 10-second intervals
monitor.startMonitoring(10000);
`
`javascript
const MemoryMonitor = require("memvigil");
// Initialize with 200MB threshold
const monitor = new MemoryMonitor(200 1024 1024);
// Start monitoring with 10-second intervals
monitor.startMonitoring(10000);
`
`javascript
const MemoryMonitor = require("memvigil");
const options = {
enableGC: true,
enablePredictions: true,
alertThresholds: {
warning: 150 1024 1024, // 150MB
critical: 200 1024 1024, // 200MB
},
};
const monitor = new MemoryMonitor(100 1024 1024, 1000, options);
// Listen for warning alerts
monitor.on("warningAlert", (alert) => {
console.log("Warning:", alert.message);
});
// Listen for critical alerts
monitor.on("criticalAlert", (alert) => {
console.log("Critical:", alert.message);
// Take immediate action
});
monitor.startMonitoring(5000);
`
`javascriptMemory trend: ${trend.direction}
monitor.on("memoryTrend", (trend) => {
console.log();Rate: ${(trend.rate / 1024).toFixed(2)} KB/s
console.log();Predicted memory in 1 hour: ${(trend.prediction / 1024 / 1024).toFixed(
console.log(
2
)} MB
);
});
// Or get trend manually
const trend = monitor.analyzeMemoryTrend();
if (trend && trend.direction === "increasing") {
console.log("Memory is growing!");
}
`
`javascriptMemory pressure level: ${pressure.pressureLevel}
const pressure = monitor.detectMemoryPressure();
if (pressure.isUnderPressure) {
console.log();
console.log("Contributing factors:", pressure.factors);
if (pressure.pressureLevel === "critical") {
// Take emergency action
monitor.takeHeapSnapshot();
}
}
`
`javascript
// Export to JSON
const jsonPath = await monitor.exportReport("json", "./memory-report.json");
console.log("Report exported to:", jsonPath);
// Export to CSV
const csvPath = await monitor.exportReport("csv", "./memory-report.csv");
console.log("CSV exported to:", csvPath);
`
`javascript
const stats = monitor.getStatistics();
console.log("Memory Statistics:");
console.log(
Current: ${(stats.memory.current.heapUsed / 1024 / 1024).toFixed(2)} MB Average: ${(stats.memory.average / 1024 / 1024).toFixed(2)} MB
);
console.log(); Peak: ${(stats.memory.peak.value / 1024 / 1024).toFixed(
console.log(
2
)} MB at ${new Date(stats.memory.peak.timestamp)}
);
console.log("CPU Statistics:");
console.log( Current user: ${stats.cpu.current.user}Ξs); Average user: ${stats.cpu.average.user}Ξs
console.log();
console.log("Performance Impact:");
console.log( Average: ${stats.performance.averageTimeMs.toFixed(3)} ms); Total samples: ${stats.performance.count}
console.log();`
`javascriptLeak detected with ${result.severity} severity
monitor.on("leakDetected", (result) => {
console.log();Trend: ${(result.trend * 100).toFixed(2)}%
console.log();
console.log("Suggestions:", result.suggestions);
if (result.severity === "critical") {
// Automatically take heap snapshot
monitor.takeHeapSnapshot();
}
});
// Run leak detection
await monitor.detectLeaks(60000, 0.1, 5);
`
1. Appropriate Monitoring Intervals
`javascript`
// Use longer intervals in production
monitor.startMonitoring(30000); // 30 seconds
2. Resource Management
`javascript`
// Clean up old snapshots
monitor.on("heapSnapshot", (filePath) => {
// Keep only last 5 snapshots
cleanupOldSnapshots(5);
});
3. Error Handling
`javascript`
monitor.on("error", (error) => {
logger.error("Memory monitor error:", error);
});
4. Performance Impact Monitoring
`javascript`
setInterval(() => {
const impact = monitor.getPerformanceImpact();
if (impact.averageTimeMs > 100) {
// If overhead exceeds 100ms
monitor.stopMonitoring();
}
}, 60000);
memvigil includes full TypeScript definitions. Simply import and use with full type safety:
`typescript
import MemoryMonitor, { MonitorOptions, MemoryTrend } from "memvigil";
const options: MonitorOptions = {
enableGC: true,
enablePredictions: true,
alertThresholds: {
warning: 150 1024 1024,
critical: 200 1024 1024,
},
};
const monitor = new MemoryMonitor(100 1024 1024, 1000, options);
monitor.on("memoryTrend", (trend: MemoryTrend) => {
console.log(Trend: ${trend.direction}, Prediction: ${trend.prediction});
});
monitor.startMonitoring(5000);
`
All types are exported and available for use in your TypeScript projects.
`javascript`
new MemoryMonitor(threshold?, maxHistorySize?, options?)
- threshold (number, default: 100MB): Memory threshold in bytesmaxHistorySize
- (number, default: 1000): Maximum history entries to keepoptions
- (object, optional):enableGC
- (boolean, default: true): Enable garbage collection trackingenablePredictions
- (boolean, default: true): Enable memory trend predictionsalertThresholds
- (object, optional):warning
- (number): Warning threshold in bytescritical
- (number): Critical threshold in bytes
- startMonitoring(interval?) - Start monitoring (default: 5000ms)stopMonitoring()
- - Stop monitoringtakeHeapSnapshot(automatic?)
- - Generate heap snapshotgetMemoryUsageReport()
- - Get memory historygetCpuUsageReport()
- - Get CPU historygetGCReport()
- - Get GC historyclearHistory()
- - Clear all historydetectLeaks(duration?, threshold?, samples?)
- - Detect memory leaksanalyzeMemoryTrend()
- - Analyze memory trendsdetectMemoryPressure()
- - Detect memory pressuregetStatistics()
- - Get comprehensive statisticsexportReport(format?, filePath?)
- - Export report (json/csv)getMemoryBreakdown()
- - Get detailed memory breakdowngetPerformanceImpact()
- - Get performance impact metricscheckNodeCompatibility()
- - Check Node.js version compatibility
- thresholdExceeded - Emitted when memory exceeds thresholdmemoryStats
- - Emitted on each memory measurementcpuStats
- - Emitted on each CPU measurementleakDetected
- - Emitted when a leak is detectedheapSnapshot
- - Emitted when a heap snapshot is createdmemoryTrend
- - Emitted when memory trend is analyzedwarningAlert
- - Emitted when warning threshold is exceededcriticalAlert
- - Emitted when critical threshold is exceededgcStats
- - Emitted on GC statistics updatereportExported
- - Emitted when a report is exportederror
- - Emitted on errorswarning
- - Emitted for warningsinfo` - Emitted for informational messages
-
MIT License - see LICENSE file for details