UNPKG

memory-watch

Version:

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

98 lines (81 loc) • 2.73 kB
const { MemoryWatch } = require("../dist/index"); // Simple test to verify user code tracking const watch = new MemoryWatch({ threshold: 0.3, // Low threshold for immediate trigger interval: 1000, // Check every second actions: [ (data) => { console.log("\n🚨 MEMORY ALERT 🚨"); console.log(`Memory Usage: ${(data.percentage * 100).toFixed(1)}%`); console.log(`Used: ${Math.round(data.usedBytes / 1024 / 1024)}MB`); console.log("\nšŸ“ STACK TRACE:"); if (data.context?.stackTrace && data.context.stackTrace.length > 0) { data.context.stackTrace.forEach((trace, index) => { const prefix = trace.fileName && trace.fileName.includes("test-user-tracking") ? "⭐" : " "; console.log(`${prefix} ${index + 1}. ${trace.functionName}`); if (trace.fileName) { console.log(` → ${trace.fileName}:${trace.lineNumber}`); } }); } else { console.log(" No stack trace available"); } console.log("\n" + "=".repeat(50)); }, ], }); // Test functions that will show up in stack trace function memoryHeavyFunction() { console.log("šŸ”§ Running memoryHeavyFunction..."); // Manually capture context watch.captureContext("memoryHeavyFunction", __filename, 35); // Create memory usage const largeArray = []; for (let i = 0; i < 50000; i++) { largeArray.push({ id: i, data: new Array(100).fill(`item-${i}`), metadata: { timestamp: new Date(), extra: new Array(50).fill(`meta-${i}`), }, }); } console.log(`āœ… Created ${largeArray.length} items`); return largeArray; } function apiSimulation() { console.log("🌐 API simulation starting..."); // Capture this function context watch.captureContext("apiSimulation", __filename, 56); // Call the memory heavy function const result = memoryHeavyFunction(); // Do some more processing const processed = result.map((item) => ({ ...item, processed: true, extraData: new Array(20).fill(`processed-${item.id}`), })); console.log("āœ… API simulation completed"); return processed; } console.log("šŸš€ Testing User Code Tracking..."); console.log("Features:"); console.log("- Manual context capture with captureContext()"); console.log("- Improved stack trace detection"); console.log("- User code highlighting\n"); watch.start(); // Test sequence setTimeout(() => { console.log("Starting memory-intensive operations..."); apiSimulation(); }, 2000); // Stop after 10 seconds setTimeout(() => { watch.stop(); console.log("\nāœ… Test completed - Memory tracking stopped"); process.exit(0); }, 10000);