A comprehensive performance profiling utility for Node.js applications with timing, memory monitoring, and garbage collection tracking. Perfect for debugging performance issues, memory leaks, and optimizing application performance.
npm install @crudmates/profilerA comprehensive Node.js profiler that combines function-level timing, V8 performance analysis, and memory monitoring in a production-safe package. Designed for both development debugging and continuous production monitoring.
``bash`
npm install @crudmates/profiler
Perfect for profiling API endpoints, database queries, or any specific function:
`typescript
import { profile } from '@crudmates/profiler';
// Profile any function with timing + memory
const { result, profile: stats } = await profile(
() => expensiveOperation(),
'expensiveOperation',
{
trackMemory: true,
enableGC: true,
tags: { operation: 'database' }
}
);
console.log(${stats.name} took ${stats.duration}ms);Memory delta: ${stats.memDelta?.heapUsed}MB
console.log();`
NEW! Deep performance analysis for production applications:
`typescript
import { V8Profiler } from '@crudmates/profiler';
// Start continuous profiling with automatic 60-min intervals
const v8Profiler = new V8Profiler('production-api', {
maxMemoryBudgetMB: 100, // Hard memory limit
intervalMinutes: 60, // Auto-log every hour
cpuProfiling: true, // Find performance bottlenecks
samplingHeapProfiler: true, // Track memory allocations
});
await v8Profiler.startContinuousProfiling();
// Runs indefinitely, logs insights every 60 minutes
// Zero memory buildup, actionable insights only
// Later...
const insights = await v8Profiler.stopContinuousProfiling();
console.log('Top CPU consumers:', insights.topFunctions);
console.log('Memory hot spots:', insights.memoryHotspots);
`
Zero-friction profiling with decorators:
`typescript
import { Profile } from '@crudmates/profiler';
class UserService {
@Profile('fetchUsers', { trackMemory: true })
async fetchUsers() {
return await this.userRepository.find();
}
}
`
Lightweight timing without overhead:
`typescript
import { Timer } from '@crudmates/profiler';
const timer = new Timer('database-query');
const users = await db.users.find();
timer.stop({ userCount: users.length });
// Or static method
const result = await Timer.time(() => processData(), 'processData');
`
Track memory usage patterns over time:
`typescript
import { MemMonitor } from '@crudmates/profiler';
const monitor = new MemMonitor();
monitor.snap('start');
await processLargeDataset();
monitor.snap('after-processing');
monitor.compare('start', 'after-processing');
`
Multi-step profiling with checkpoints:
`typescript
import { Profiler } from '@crudmates/profiler';
const profiler = new Profiler('batch-processing', {
enableGC: true,
gcThresholdMB: 100
});
profiler.start();
for (const batch of batches) {
profiler.mark(processing-batch-${batch.id});`
await processBatch(batch);
}
const summary = profiler.end();
The V8Profiler sets this package apart from basic timing libraries. It provides the deep insights of clinic.js or 0x, but designed for continuous production monitoring:
`typescript`
const profiler = new V8Profiler('my-app', {
maxMemoryBudgetMB: 50, // Required: Hard memory limit
intervalMinutes: 120, // Custom interval (2 hours)
cpuProfiling: true, // CPU bottleneck analysis
samplingHeapProfiler: true, // Memory allocation tracking
suppressWarnings: false // Get configuration guidance
});
Unlike tools that dump massive profile files, we return structured insights:
`typescript
const insights = await profiler.flushCurrentInterval();
// CPU Performance
insights.topFunctions.forEach(fn => {
console.log(${fn.functionName}: ${fn.selfTime}ms (${fn.percentage}%));
});
// Memory Analysis
insights.memoryHotspots.forEach(spot => {
console.log(${spot.allocation}: ${spot.size} bytes (${spot.count} allocations));
});
// Current memory state
console.log(Heap: ${insights.memoryUsage.heap});RSS: ${insights.memoryUsage.rss}
console.log();`
The maxMemoryBudgetMB requirement prevents profiling from becoming the problem:
`typescript
// ✅ Safe - enforces memory limits
const profiler = new V8Profiler('app', {
maxMemoryBudgetMB: 100, // Required parameter
intervalMinutes: 240 // 4 hours
});
// ⚠️ Gets helpful warnings:
// "High memory risk: 240min interval may use ~360MB, approaching limit of 100MB"
// "Consider: reducing intervalMinutes to 53 or increasing maxMemoryBudgetMB to 432"
`
Built-in leak detection for proactive monitoring:
`typescript
import { detectMemLeak } from '@crudmates/profiler';
const measurements = [];
for (let i = 0; i < 10; i++) {
measurements.push(process.memoryUsage());
await someOperation();
}
const analysis = detectMemLeak(measurements, 50); // 50MB threshold
if (analysis.isLeaking) {
console.warn(Memory leak detected! Trend: ${analysis.trend}, Growth: ${analysis.avgGrowth}MB);`
}
| Feature | @crudmates/profiler | clinic.js | 0x | --prof | perf_hooks |
|---------|:---------------------:|:-----------:|:----:|:--------:|:------------:|
| Function-level timing | ✅ | ❌ | ❌ | ❌ | ⚠️ Manual |
| V8 CPU profiling | ✅ | ✅ | ✅ | ✅ | ❌ |
| Memory allocation tracking | ✅ | ✅ | ❌ | ❌ | ❌ |
| Zero disk writes | ✅ | ❌ | ❌ | ❌ | ✅ |
| Production-safe intervals | ✅ | ❌ | ❌ | ❌ | ❌ |
| Memory budget protection | ✅ | ❌ | ❌ | ❌ | ❌ |
| TypeScript native | ✅ | ⚠️ | ⚠️ | ❌ | ⚠️ |
| Async/await support | ✅ | ⚠️ | ⚠️ | ⚠️ | ⚠️ |
| Single dependency | ✅ | ❌ | ❌ | ✅ | ✅ |
- Function-level profiling (microseconds) - For API endpoints, database queries
- Application-level V8 profiling (minutes/hours) - Deep CPU and memory analysis
- Memory monitoring with leak detection - Real-time tracking without overhead
- Checkpoint system for complex workflows - Mark and measure any process step-by-step
- Zero disk I/O - Everything stays in memory with configurable budgets
- Memory budget enforcement - Hard limits prevent profiling from causing issues
- Automatic interval flushing - Long-running profiling without memory buildup
- Smart configuration warnings - Helps avoid problematic settings
- Async/await native - No callback hell or promise wrapping
- TypeScript first - Full type safety and IntelliSense
- Production logging integration - Works with your existing logger
- Configurable everything - From silent mode to verbose debugging
Key insight: While other tools excel in specific areas, this profiler bridges the gap between development debugging and production monitoring, with built-in safety features to prevent profiling from impacting your application's performance.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| trackMemory | boolean | true | Enable memory usage tracking |enableGC
| | boolean | false | Enable garbage collection monitoring |gcThresholdMB
| | number | 100 | Memory threshold to trigger GC |logger
| | Logger \| Console | console | Custom logger instance |tags
| | RecordlogLevel
| | 'debug' \| 'log' \| 'verbose' | 'debug' | Logging verbosity |verbose
| | boolean | false | Detailed step-by-step logging |silent
| | boolean | false | Disable all logging output |
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| maxMemoryBudgetMB | number | Required | Hard memory limit for profiling data |intervalMinutes
| | number | 60 | Auto-flush interval (prevents buildup) |cpuProfiling
| | boolean | true | Enable CPU performance analysis |samplingHeapProfiler
| | boolean | true | Enable memory allocation tracking |streamingMode
| | boolean | true | Process data incrementally |suppressWarnings
| | boolean | false | Hide configuration warnings |logger
| | Logger \| Console | console | Custom logger instance |
for memory-intensive operations
- Add meaningful tags for categorization$3
- Use for application-level analysis (> 1 minute duration)
- Start with 60-minute intervals in production
- Set maxMemoryBudgetMB based on available system memory
- Use suppressWarnings: true once configuration is stable$3
- Always run with --expose-gc when using GC features
- Monitor memory trends with detectMemLeak()
- Use higher gcThresholdMB values in production$3
- Use verbose: true for debugging, silent: true for production
- Integrate with your application's logger instance
- Add contextual tags for better filteringRequirements
- Node.js >= 14.0.0
- TypeScript >= 5.0.0 (for TypeScript users)
- Run with
--expose-gc for garbage collection features
- Run with --inspect for V8 profiling features (development)License
MIT License - see LICENSE file for details.
---
Ready to optimize your Node.js applications? Install
@crudmates/profiler` and start profiling with confidence! 🚀