Main API function for integrating flamegraph profiling into Node.js applications and tooling workflows.
Profiles a Node.js process and generates flamegraph visualization or collects profiling data.
/**
* Profile a Node.js process and generate flamegraph visualization
* @param args - Profiling configuration options (validated against schema)
* @returns Promise resolving to flamegraph file path or data folder path
* @throws Error if arguments are invalid or profiling fails
*/
function zeroEks(args: ProfilingOptions): Promise<string>;Usage Examples:
const zeroEks = require('0x');
// Basic profiling with flamegraph generation
const result = await zeroEks({
argv: ['server.js'],
name: 'my-server-profile',
title: 'Server Performance Profile'
});
console.log(`Flamegraph available at: ${result}`);
// Data collection only for later analysis
const dataFolder = await zeroEks({
argv: ['server.js'],
collectOnly: true,
outputDir: './profiles/{name}-{timestamp}',
treeDebug: true,
writeTicks: true
});
// Load testing integration
const profile = await zeroEks({
argv: ['server.js'],
onPort: 'autocannon -c 100 -d 30 localhost:$PORT',
open: true
});
// Custom Node.js binary and kernel tracing
const kernelProfile = await zeroEks({
argv: ['--max-old-space-size=4096', 'memory-intensive-app.js'],
pathToNodeBinary: '/usr/local/bin/node',
kernelTracing: true,
collectDelay: 5000
});Functions for processing existing profiling data without collecting new data.
// Visualize existing profiling data folder
const flamegraph = await zeroEks({
visualizeOnly: './1234.0x',
title: 'Previous Run Analysis',
open: true
});
// Visualize V8 CPU profile
const cpuProfile = await zeroEks({
visualizeCpuProfile: './profile.cpuprofile',
name: 'cpu-analysis'
});Complete configuration interface for the main zeroEks function.
interface ProfilingOptions {
// Required
/** Command line arguments for target process */
argv: string[];
// Basic Options
/** Output name prefix for generated files (default: "flamegraph") */
name?: string;
/** Flamegraph title (default: constructed from argv) */
title?: string;
// Output Control
/** Output directory pattern with template variables */
outputDir?: string;
/** Output HTML file pattern with template variables */
outputHtml?: string;
/** Automatically open flamegraph in browser */
open?: boolean;
// Profiling Modes
/** Only collect profiling data, don't generate flamegraph */
collectOnly?: boolean;
/** Visualize existing profiling data from folder path */
visualizeOnly?: string;
/** Visualize existing V8 CPU profile from file path */
visualizeCpuProfile?: string;
// Platform Options
/** Use Linux kernel tracing instead of V8 profiling */
kernelTracing?: boolean;
/** Path to Node.js binary to profile (default: process.execPath) */
pathToNodeBinary?: string;
/** Working directory for profiling operations (default: process.cwd()) */
workingDir?: string;
// Timing Options
/** Delay before starting data collection (milliseconds) */
collectDelay?: number;
// Load Testing Integration
/** Command or function to execute when port is detected */
onPort?: string | OnPortFunction;
// Debug Options
/** Enable frame mapping for better stack trace resolution */
mapFrames?: boolean;
/** Generate debug tree data file */
treeDebug?: boolean;
/** Write raw tick data to file */
writeTicks?: boolean;
// Callbacks
/** Callback function for process exit events */
onProcessExit?: () => void;
/** Status reporting callback function */
status?: (message: string) => void;
}
type OnPortFunction = (port: number, callback: (error?: Error) => void) => void;Output directory and HTML file patterns support template variables:
// Available template variables in outputDir and outputHtml
interface TemplateVariables {
/** Process ID of profiled application */
'{pid}': string;
/** Timestamp when profiling started */
'{timestamp}': number;
/** Current working directory */
'{cwd}': string;
/** Name specified in options */
'{name}': string;
/** Output directory path (for outputHtml) */
'{outputDir}': string;
}Template Examples:
// Custom output patterns
await zeroEks({
argv: ['app.js'],
name: 'production-profile',
outputDir: './profiles/{name}-{timestamp}',
outputHtml: '{outputDir}/flamegraph-{pid}.html'
});The zeroEks function validates all arguments and can throw various errors:
// Validation errors for invalid arguments
class ValidationError extends Error {
constructor(message: string);
}
// Platform errors for unsupported configurations
class PlatformError extends Error {
constructor(message: string);
}
// Process errors for target application failures
class ProcessError extends Error {
constructor(message: string);
code?: number;
}Error Handling Examples:
try {
const result = await zeroEks({
argv: ['nonexistent-script.js'],
kernelTracing: true // Linux only
});
} catch (error) {
if (error.message.includes('option')) {
console.error('Configuration error:', error.message);
} else if (error.message.includes('platform')) {
console.error('Platform incompatibility:', error.message);
} else {
console.error('Profiling failed:', error.message);
}
}const zeroEks = require('0x');
async function profileProduction() {
// Collect data only for analysis later
const dataFolder = await zeroEks({
argv: ['server.js'],
collectOnly: true,
collectDelay: 10000, // Wait 10s for server startup
outputDir: '/var/log/profiles/{name}-{timestamp}',
name: 'production-server'
});
// Later: visualize the collected data
const flamegraph = await zeroEks({
visualizeOnly: dataFolder,
title: 'Production Server Profile',
outputHtml: '/var/www/html/profiles/latest.html'
});
return { dataFolder, flamegraph };
}async function profileWithCustomTesting() {
return zeroEks({
argv: ['api-server.js'],
onPort: async (port, callback) => {
try {
// Custom load testing logic
await runCustomLoadTest(port);
callback(); // Signal completion
} catch (err) {
callback(err); // Signal error
}
},
open: true
});
}
async function runCustomLoadTest(port) {
// Custom implementation
const response = await fetch(`http://localhost:${port}/health`);
// ... additional testing logic
}