UNPKG

memory-watch

Version:

Advanced Node.js memory monitoring with stack trace analysis, user code detection, and memory leak identification

83 lines (71 loc) 2.5 kB
const { MemoryWatch } = require("../dist/index"); // Example usage of MemoryWatch const watch = new MemoryWatch({ threshold: 0.8, // 80% of max heap interval: 30000, // Check every 30 seconds continuous: true, // Continue monitoring after reaching threshold actions: [ (data) => { // Example 1: Simple logging console.log("🚨 Memory threshold reached!"); console.log(`Usage: ${(data.percentage * 100).toFixed(2)}%`); console.log(`Amount: ${data.usedBytes} / ${data.totalBytes} bytes`); console.log(`Time: ${data.timestamp}`); console.log(`Trigger source: ${data.context?.triggerSource}`); console.log("---"); }, async (data) => { // Example 2: Send Slack notification (you need to implement this) console.log("Sending Slack notification:", { message: `Memory usage reached ${(data.percentage * 100).toFixed(2)}%`, timestamp: data.timestamp, process: data.context?.pid, platform: data.context?.platform, }); // Here you can write the actual Slack sending code // await sendSlackNotification(data); }, (data) => { // Example 3: Save to log file const logMessage = `[${data.timestamp.toISOString()}] Memory Alert: ${( data.percentage * 100 ).toFixed(2)}% used (${data.usedBytes}/${ data.totalBytes } bytes) - Trigger: ${data.context?.triggerSource}\n`; // Here you can write the file writing code console.log("Log message to save:", logMessage); // require('fs').appendFileSync('./memory-alerts.log', logMessage); }, ], }); // Start monitoring watch.start(); console.log("Memory monitoring started..."); console.log("Press Ctrl+C to stop"); // Example usage of static method for one-time check MemoryWatch.checkOnce(0.5).then((result) => { if (result) { console.log("Memory usage is above 50%:", result); } else { console.log("Memory usage is below 50%"); } }); // Sample function to create memory pressure (for testing) function createMemoryPressure() { const arrays = []; for (let i = 0; i < 1000; i++) { arrays.push(new Array(10000).fill(Math.random())); } return arrays; } // Test memory pressure after 5 seconds setTimeout(() => { console.log("Creating memory pressure for testing..."); createMemoryPressure(); }, 5000); // Stop after 2 minutes setTimeout(() => { watch.stop(); console.log("Memory monitoring stopped"); process.exit(0); }, 120000);