memory-watch
Version:
Advanced Node.js memory monitoring with stack trace analysis, user code detection, and memory leak identification
95 lines (83 loc) โข 2.88 kB
JavaScript
const {
MemoryWatch,
generateDiagnosticReport,
getMemoryLeakIndicators,
} = require("../dist/index");
// Test with very low threshold to see immediate results
const watch = new MemoryWatch({
threshold: 0.3, // 30% threshold - very low for immediate trigger
interval: 3000, // Check every 3 seconds
actions: [
(data) => {
console.log("\n" + "=".repeat(50));
console.log("๐จ LOW THRESHOLD TEST - MEMORY ALERT!");
console.log("=".repeat(50));
// Show basic info first
console.log(`๐ Memory Usage: ${(data.percentage * 100).toFixed(1)}%`);
console.log(
`๐พ Used: ${Math.round(data.usedBytes / 1024 / 1024)}MB / ${Math.round(
data.totalBytes / 1024 / 1024
)}MB`
);
// Show stack trace - the most important part
if (data.context?.stackTrace && data.context.stackTrace.length > 0) {
console.log("\n๐ STACK TRACE (What caused this):");
data.context.stackTrace.slice(0, 5).forEach((trace, index) => {
if (trace.fileName && !trace.fileName.includes("node:")) {
console.log(
` ${index + 1}. ๐ฏ ${trace.functionName} โ ${trace.fileName}:${
trace.lineNumber
}`
);
} else {
console.log(` ${index + 1}. ${trace.functionName}`);
}
});
}
// Show trigger source
if (data.context?.triggerSource) {
console.log(`\n๐ Trigger: ${data.context.triggerSource}`);
}
// Quick memory breakdown
console.log("\n๐ Memory Details:");
console.log(
` Heap: ${Math.round(data.breakdown.heapUsed / 1024 / 1024)}MB`
);
console.log(` RSS: ${Math.round(data.breakdown.rss / 1024 / 1024)}MB`);
console.log(
` External: ${Math.round(data.breakdown.external / 1024)}KB`
);
// Process info
console.log("\n๐ฅ๏ธ Process:");
console.log(` PID: ${data.context?.pid}`);
console.log(` Uptime: ${Math.round(data.context?.uptime || 0)}s`);
console.log(` Active Handles: ${data.context?.activeHandles}`);
console.log("=".repeat(50) + "\n");
},
],
});
console.log("๐งช Testing with LOW threshold (30%) for immediate results...");
watch.start();
// Simulate some memory usage
function createSmallMemoryUsage() {
const data = [];
for (let i = 0; i < 500; i++) {
data.push({
id: i,
content: new Array(100).fill(`data-${i}`),
});
}
console.log(`๐ Created small memory usage: ${data.length} items`);
return data;
}
// Create memory usage after 2 seconds
setTimeout(() => {
console.log("Creating initial memory usage...");
createSmallMemoryUsage();
}, 2000);
// Stop after 15 seconds
setTimeout(() => {
watch.stop();
console.log("โ
Test completed");
process.exit(0);
}, 15000);