### Install Dependencies (npm) Source: https://github.com/google/pprof-nodejs/blob/main/CONTRIBUTING.md Installs the necessary dependencies for the project using npm. This is a prerequisite for running tests and other development tasks. ```sh npm install ``` -------------------------------- ### Run System Test (Shell) Source: https://github.com/google/pprof-nodejs/blob/main/CONTRIBUTING.md Executes the system test script, which starts a benchmark, collects profile data using the module, and verifies the profiles. Requires Go installation. ```sh sh system-test/system_test.sh ``` -------------------------------- ### Start Node.js with pprof from command line Source: https://github.com/google/pprof-nodejs/blob/main/README.md This command-line instruction shows how to start a Node.js application with the pprof module automatically required. This method automatically saves a wall time profile upon application completion. ```sh node --require pprof app.js ``` -------------------------------- ### Install pprof with npm Source: https://github.com/google/pprof-nodejs/blob/main/README.md Installs the pprof module using npm and saves it to the local 'package.json'. This is a foundational step for using pprof in a Node.js project. ```sh # Install through npm while saving to the local 'package.json' npm install --save pprof ``` -------------------------------- ### Heap Profiler - Setup and Collection API Source: https://context7.com/google/pprof-nodejs/llms.txt This API allows you to capture memory allocation patterns by sampling heap allocations. It helps in identifying memory-intensive code paths and potential memory leaks by collecting heap profiles in the pprof format. ```APIDOC ## Heap Profiler - Setup and Collection ### Description Captures memory allocation patterns by sampling heap allocations at specified intervals. Identifies memory-intensive code paths and potential memory leaks. ### Method - **Start:** `pprof.heap.start(intervalBytes, stackDepth)` - **Profile:** `pprof.heap.profile()` - **Stop:** `pprof.heap.stop()` ### Parameters #### Start Parameters - **intervalBytes** (number) - Required - Sample every X bytes allocated. - **stackDepth** (number) - Required - Maximum call stack depth to record. ### Request Example ```javascript const pprof = require('pprof'); const fs = require('fs').promises; async function setupAndCollectHeapProfile() { try { const intervalBytes = 512 * 1024; const stackDepth = 64; pprof.heap.start(intervalBytes, stackDepth); console.log('Heap profiling started'); await runApplication(); const profile = await pprof.heap.profile(); const buf = await pprof.encode(profile); await fs.writeFile('heap-profile.pb.gz', buf); console.log('Heap profile saved to heap-profile.pb.gz'); pprof.heap.stop(); } catch (err) { console.error('Heap profiling error:', err); pprof.heap.stop(); } } async function runApplication() { const data = []; for (let i = 0; i < 1000; i++) { data.push(Buffer.alloc(1024 * 100)); await new Promise(resolve => setTimeout(resolve, 10)); } return data; } setupAndCollectHeapProfile(); ``` ### Response #### Success Response (Object) - **profile** (Object) - The collected heap profile object. #### Response Example ```json { "profile": { /* pprof profile object structure */ } } ``` ``` -------------------------------- ### Enable heap profiling with pprof Source: https://github.com/google/pprof-nodejs/blob/main/README.md This JavaScript code configures and starts the heap profiler in a Node.js application. It specifies the sampling interval in bytes and the maximum stack depth for collected samples. ```javascript // The average number of bytes between samples. const intervalBytes = 512 * 1024; // The maximum stack depth for samples collected. const stackDepth = 64; heap.start(intervalBytes, stackDepth); ``` -------------------------------- ### Time Profiler - Manual Start/Stop API Source: https://context7.com/google/pprof-nodejs/llms.txt This API provides manual control over profiling sessions with explicit start and stop calls. It is useful for profiling specific code sections or long-running operations, allowing for custom sampling intervals and profile naming. ```APIDOC ## Time Profiler - Manual Start/Stop ### Description Provides manual control over profiling sessions with explicit start and stop calls. Useful for profiling specific code sections or long-running operations. ### Method - **Start:** `pprof.time.start(intervalMicros, name, sourceMapper, lineNumbers)` - **Stop:** `stop()` (returns the profile object) ### Parameters #### Start Parameters - **intervalMicros** (number) - Required - Sample every X microseconds. - **name** (string) - Optional - A name for the profile. - **sourceMapper** (object) - Optional - Source map support object. - **lineNumbers** (boolean) - Optional - If true, aggregate at line number level. Defaults to false. ### Request Example ```javascript const pprof = require('pprof'); const fs = require('fs'); function profileSpecificOperation() { const stop = pprof.time.start(500, 'my-operation', undefined, false); performExpensiveOperation(); doSomeWork(); const profile = stop(); const buffer = pprof.encodeSync(profile); fs.writeFileSync('operation-profile.pb.gz', buffer); console.log('Operation profiling complete'); } function performExpensiveOperation() { let sum = 0; for (let i = 0; i < 10000000; i++) { sum += Math.sqrt(i); } return sum; } function doSomeWork() { const data = Array(1000).fill(0).map((_, i) => i * 2); return data.reduce((a, b) => a + b, 0); } profileSpecificOperation(); ``` ### Response #### Success Response (Object) - **profile** (Object) - The collected profile object after calling `stop()`. #### Response Example ```json { "profile": { /* pprof profile object structure */ } } ``` ``` -------------------------------- ### Express.js CPU and Heap Profiling with pprof-nodejs Source: https://context7.com/google/pprof-nodejs/llms.txt This snippet demonstrates a complete Express.js application setup for profiling using pprof-nodejs. It includes endpoints for collecting CPU and heap profiles on demand, simulating application load, and handling graceful shutdown to save final profiles. It requires 'pprof', 'express', and 'fs'. Outputs profile data in pprof format. ```javascript const pprof = require('pprof'); const express = require('express'); const fs = require('fs').promises; const app = express(); let heapProfilingStarted = false; // Start heap profiling on application startup app.on('mount', () => { if (!heapProfilingStarted) { pprof.heap.start(512 * 1024, 64); heapProfilingStarted = true; console.log('Heap profiling started'); } }); // Endpoint to trigger CPU profile collection app.get('/profile/cpu', async (req, res) => { try { const duration = parseInt(req.query.duration) || 10000; console.log(`Starting CPU profile for ${duration}ms`); const profile = await pprof.time.profile({ durationMillis: duration, intervalMicros: 1000 }); const buf = await pprof.encode(profile); const filename = `cpu-${Date.now()}.pb.gz`; await fs.writeFile(filename, buf); res.json({ success: true, filename, size: buf.length, duration }); } catch (err) { res.status(500).json({ error: err.message }); } }); // Endpoint to collect heap profile app.get('/profile/heap', async (req, res) => { try { if (!heapProfilingStarted) { return res.status(400).json({ error: 'Heap profiling not started' }); } const profile = pprof.heap.profile(); const buf = await pprof.encode(profile); const filename = `heap-${Date.now()}.pb.gz`; await fs.writeFile(filename, buf); res.json({ success: true, filename, size: buf.length }); } catch (err) { res.status(500).json({ error: err.message }); } }); // Simulate CPU-intensive endpoint app.get('/api/compute', (req, res) => { const iterations = parseInt(req.query.iterations) || 1000000; let result = 0; for (let i = 0; i < iterations; i++) { result += Math.sqrt(i) * Math.sin(i) * Math.cos(i); } res.json({ result, iterations }); }); // Simulate memory-intensive endpoint app.get('/api/allocate', (req, res) => { const sizeMB = parseInt(req.query.size) || 10; const buffers = []; for (let i = 0; i < sizeMB; i++) { buffers.push(Buffer.alloc(1024 * 1024)); } res.json({ allocated: `${sizeMB} MB`, buffers: buffers.length }); }); // Graceful shutdown with final profile process.on('SIGTERM', async () => { console.log('Shutting down, collecting final profiles...'); try { // Collect final heap profile if (heapProfilingStarted) { const heapProfile = pprof.heap.profile(); const heapBuf = await pprof.encode(heapProfile); await fs.writeFile('shutdown-heap.pb.gz', heapBuf); pprof.heap.stop(); } console.log('Final profiles saved'); } catch (err) { console.error('Error saving final profiles:', err); } process.exit(0); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); console.log('Profiling endpoints:'); console.log(` GET /profile/cpu?duration=10000`); console.log(` GET /profile/heap`); console.log('Test endpoints:'); console.log(` GET /api/compute?iterations=1000000`); console.log(` GET /api/allocate?size=10`); }); ``` -------------------------------- ### Application Code for Automatic Profiling Source: https://context7.com/google/pprof-nodejs/llms.txt This JavaScript code snippet represents an example application file ('app.js') that can be profiled automatically using the 'node --require pprof' command. No modifications are needed within the application code itself for the profiler to function. The code sets up a simple Express server with a route that performs a heavy computation, which will be captured by the profiler. ```javascript // app.js - No code changes needed! const express = require('express'); const app = express(); app.get('/', (req, res) => { // This will be profiled automatically const result = heavyComputation(); res.json({ result }); }); function heavyComputation() { let sum = 0; for (let i = 0; i < 1000000; i++) { sum += Math.sqrt(i) * Math.sin(i); } return sum; } app.listen(3000, () => { console.log('Server running - being profiled automatically'); }); ``` -------------------------------- ### Command-Line Profiling with --require Source: https://context7.com/google/pprof-nodejs/llms.txt Automatically profiles entire application execution by preloading the pprof module using the Node.js --require flag. This generates profile files without requiring any code modifications in the application itself. The profiler automatically starts time profiling on module load, stops on process exit, and saves the profile to a file named pprof-profile-.pb.gz. ```bash # Profile an application from the command line node --require pprof app.js # The profiler automatically: # 1. Starts time profiling when the module loads # 2. Stops profiling on process exit # 3. Saves profile to pprof-profile-.pb.gz # Run your application normally node --require pprof server.js --port 3000 # View the generated profile pprof -http=:8080 pprof-profile-12345.pb.gz ``` -------------------------------- ### Collect V8 Heap Profile Source: https://context7.com/google/pprof-nodejs/llms.txt Collects heap allocation data in V8's native format. This method is useful for custom analysis or integration with V8-specific tools. It requires the 'pprof' and 'fs.promises' modules. The function starts the heap profiler, creates test objects to generate allocations, retrieves the profile in V8 format, saves it as a JSON file, and then stops the profiler. ```javascript const pprof = require('pprof'); const fs = require('fs').promises; async function collectV8HeapProfile() { try { // Start heap profiler pprof.heap.start(512 * 1024, 64); // Allocate various objects const objects = createTestObjects(); // Get profile in V8 format const v8Profile = pprof.heap.v8Profile(); // V8 profile structure: // { // name: string, // scriptName: string, // children: AllocationProfileNode[], // allocations: [{ sizeBytes: number, count: number }] // } // Save as JSON for analysis await fs.writeFile( 'heap-v8-format.json', JSON.stringify(v8Profile, null, 2) ); console.log('V8 heap profile saved'); // Stop profiling pprof.heap.stop(); // Print summary printAllocationSummary(v8Profile); } catch (err) { if (err.message.includes('not enabled')) { console.error('Start heap profiler before collecting profiles'); } else { console.error('Error:', err); } pprof.heap.stop(); } } function createTestObjects() { const objects = { buffers: Array(100).fill(0).map(() => Buffer.alloc(10000)), arrays: Array(50).fill(0).map(() => new Array(1000).fill(Math.random())), strings: Array(200).fill(0).map((_, i) => 'test-string-'.repeat(100) + i) }; return objects; } function printAllocationSummary(profile) { let totalBytes = 0; let totalCount = 0; function traverse(node) { if (node.allocations) { node.allocations.forEach(alloc => { totalBytes += alloc.sizeBytes; totalCount += alloc.count; }); } if (node.children) { node.children.forEach(traverse); } } traverse(profile); console.log(`Total allocations: ${totalCount}`); console.log(`Total bytes: ${(totalBytes / 1024 / 1024).toFixed(2)} MB`); } collectV8HeapProfile(); ``` -------------------------------- ### Manually Control CPU Profiling with pprof-nodejs Source: https://context7.com/google/pprof-nodejs/llms.txt Provides manual control over CPU profiling sessions with explicit start and stop calls. This is useful for profiling specific code sections or long-running operations. It allows setting the sampling interval, providing a profile name, and optionally specifying a source mapper and line number aggregation. ```javascript const pprof = require('pprof'); const fs = require('fs'); function profileSpecificOperation() { // Start profiling with custom parameters const stop = pprof.time.start( 500, // intervalMicros: sample every 500μs 'my-operation', // name: profile identifier undefined, // sourceMapper: optional source map support false // lineNumbers: function-level aggregation ); // Run your code performExpensiveOperation(); doSomeWork(); // Stop profiling and get results const profile = stop(); // Synchronously encode and save const buffer = pprof.encodeSync(profile); fs.writeFileSync('operation-profile.pb.gz', buffer); console.log('Operation profiling complete'); } function performExpensiveOperation() { // Simulate CPU-intensive work let sum = 0; for (let i = 0; i < 10000000; i++) { sum += Math.sqrt(i); } return sum; } function doSomeWork() { const data = Array(1000).fill(0).map((_, i) => i * 2); return data.reduce((a, b) => a + b, 0); } profileSpecificOperation(); ``` -------------------------------- ### Collect and save a heap profile in code Source: https://github.com/google/pprof-nodejs/blob/main/README.md This JavaScript code snippet demonstrates how to collect a heap profile after enabling heap profiling and save it to a file. It uses `pprof.heap.profile` to get the profile data and `pprof.encode` for serialization. ```javascript const profile = await pprof.heap.profile(); const buf = await pprof.encode(profile); fs.writeFile('heap.pb.gz', buf, (err) => { if (err) throw err; }) ``` -------------------------------- ### Collect Heap Allocation Profile with pprof-nodejs Source: https://context7.com/google/pprof-nodejs/llms.txt Captures memory allocation patterns by sampling heap allocations at specified intervals. This helps identify memory-intensive code paths and potential memory leaks. It requires starting the heap profiler with a specified sampling interval in bytes and maximum call stack depth, then collecting the profile after application code has run. ```javascript const pprof = require('pprof'); const fs = require('fs').promises; async function setupAndCollectHeapProfile() { try { // Start heap profiling const intervalBytes = 512 * 1024; // Sample every 512KB allocated const stackDepth = 64; // Maximum call stack depth pprof.heap.start(intervalBytes, stackDepth); console.log('Heap profiling started'); // Run application code await runApplication(); // Collect heap profile in pprof format const profile = await pprof.heap.profile(); const buf = await pprof.encode(profile); await fs.writeFile('heap-profile.pb.gz', buf); console.log('Heap profile saved to heap-profile.pb.gz'); // Stop profiling pprof.heap.stop(); // View with: pprof -http=: heap-profile.pb.gz } catch (err) { console.error('Heap profiling error:', err); pprof.heap.stop(); // Cleanup on error } } async function runApplication() { // Simulate memory allocation patterns const data = []; for (let i = 0; i < 1000; i++) { data.push(Buffer.alloc(1024 * 100)); // Allocate 100KB buffers await new Promise(resolve => setTimeout(resolve, 10)); } return data; } setupAndCollectHeapProfile(); ``` -------------------------------- ### Run Tests (npm) Source: https://github.com/google/pprof-nodejs/blob/main/CONTRIBUTING.md Executes the test suite for the project using npm. This command verifies the current state of the codebase. ```sh npm test ``` -------------------------------- ### Collect V8 allocation profile with pprof Source: https://github.com/google/pprof-nodejs/blob/main/README.md This JavaScript code snippet shows how to collect a heap profile using the V8 allocation profile format. This is an alternative to the default heap profiling method and provides different insights into memory usage. ```javascript const profile = await pprof.heap.v8Profile(); ``` -------------------------------- ### Profile Encoding with pprof Source: https://context7.com/google/pprof-nodejs/llms.txt Serializes profile data into compressed pprof protobuf format. This snippet demonstrates both asynchronous and synchronous encoding methods using the 'pprof' and 'fs' modules. The asynchronous method is preferred for I/O operations, while the synchronous method is useful for exit handlers. Both methods produce identical gzipped protobuf files. ```javascript const pprof = require('pprof'); const fs = require('fs'); async function demonstrateEncoding() { // Collect a profile const profile = await pprof.time.profile({ durationMillis: 5000 }); // Async encoding (preferred for I/O operations) const asyncBuffer = await pprof.encode(profile); await fs.promises.writeFile('async-profile.pb.gz', asyncBuffer); console.log(`Async encoded: ${asyncBuffer.length} bytes`); // Sync encoding (useful for exit handlers) const syncBuffer = pprof.encodeSync(profile); fs.writeFileSync('sync-profile.pb.gz', syncBuffer); console.log(`Sync encoded: ${syncBuffer.length} bytes`); // Both produce identical gzipped protobuf files console.log('Files are identical:', asyncBuffer.equals(syncBuffer)); } // Example: Encoding in process exit handler function setupExitHandler() { const stop = pprof.time.start(); process.on('exit', () => { // Must use sync in exit handler const profile = stop(); const buffer = pprof.encodeSync(profile); fs.writeFileSync(`exit-profile-${process.pid}.pb.gz`, buffer); }); } demonstrateEncoding(); ``` -------------------------------- ### Collect CPU Wall-Time Profile with pprof-nodejs Source: https://context7.com/google/pprof-nodejs/llms.txt Collects CPU wall-time profile data over a specified duration using programmatic APIs. It allows configuration of duration, sampling interval, and aggregation level. Returns a profile object that can be encoded to the pprof format and saved to a gzipped protobuf file. ```javascript const pprof = require('pprof'); const fs = require('fs').promises; async function collectTimeProfile() { try { // Collect profile for 10 seconds with custom sampling interval const profile = await pprof.time.profile({ durationMillis: 10000, // Duration to collect profile intervalMicros: 1000, // Sampling interval (default: 1000μs) lineNumbers: false // Aggregate at function level (default) }); // Encode to gzipped protobuf format const buf = await pprof.encode(profile); // Save to file await fs.writeFile('cpu-profile.pb.gz', buf); console.log('Profile saved to cpu-profile.pb.gz'); // View with: pprof -http=: cpu-profile.pb.gz } catch (err) { console.error('Profiling error:', err); } } collectTimeProfile(); ``` -------------------------------- ### Profile Transpiled Node.js Code with Source Maps Source: https://context7.com/google/pprof-nodejs/llms.txt This snippet demonstrates how to use pprof's SourceMapper to map profiling data from transpiled JavaScript code back to the original TypeScript or Babel source files. It's essential for debugging applications built with modern JavaScript toolchains. It requires the 'pprof' and 'fs' modules. ```javascript const pprof = require('pprof'); const fs = require('fs').promises; async function profileWithSourceMaps() { try { // Create source mapper for TypeScript/transpiled code const sourceMapper = await pprof.SourceMapper.create([ './dist', // Directory containing .js and .js.map files './build', // Additional search directory './out' ]); console.log('Source maps loaded'); // Time profiling with source mapping const timeProfile = await pprof.time.profile({ durationMillis: 10000, sourceMapper: sourceMapper, // Map to original source lineNumbers: true // Line-level precision }); const timeBuf = await pprof.encode(timeProfile); await fs.writeFile('typescript-profile.pb.gz', timeBuf); // Heap profiling with source mapping pprof.heap.start(512 * 1024, 64); await runTranspiledCode(); const heapProfile = pprof.heap.profile( undefined, // ignoreSamplePath sourceMapper // Map allocations to source ); const heapBuf = await pprof.encode(heapProfile); await fs.writeFile('typescript-heap.pb.gz', heapBuf); pprof.heap.stop(); // Profiles now show original TypeScript filenames and line numbers console.log('Profiles mapped to TypeScript source'); } catch (err) { console.error('Source mapping error:', err); } } async function runTranspiledCode() { // Your transpiled application code const data = Array(1000).fill(0).map((_, i) => ({ id: i, data: Buffer.alloc(10000) })); return data; } profileWithSourceMaps(); ``` -------------------------------- ### Collect and save a wall time profile in code Source: https://github.com/google/pprof-nodejs/blob/main/README.md This JavaScript code snippet demonstrates how to programmatically collect a wall time profile for a specified duration and save it to a file. It utilizes the `pprof.time.profile` function and `pprof.encode` for serialization. ```javascript const profile = await pprof.time.profile({ durationMillis: 10000, // time in milliseconds for which to // collect profile. }); const buf = await pprof.encode(profile); fs.writeFile('wall.pb.gz', buf, (err) => { if (err) throw err; }); ``` -------------------------------- ### Advanced Node.js Time Profiling with Line Numbers Source: https://context7.com/google/pprof-nodejs/llms.txt This snippet shows how to enable line-level profiling granularity using the pprof library, providing more detailed performance insights within functions. It's useful for identifying performance bottlenecks at a very granular level. It requires the 'pprof' and 'fs' modules. ```javascript const pprof = require('pprof'); const fs = require('fs').promises; async function lineLevelProfiling() { try { // Profile with line-level granularity const profile = await pprof.time.profile({ durationMillis: 8000, intervalMicros: 500, // More frequent sampling lineNumbers: true, // Enable line-level profiling name: 'line-level-profile' }); const buf = await pprof.encode(profile); await fs.writeFile('line-level.pb.gz', buf); console.log('Line-level profile collected'); // View with pprof to see hot lines within functions // pprof -http=: line-level.pb.gz } catch (err) { console.error('Error:', err); } } // Example function that benefits from line-level profiling function complexFunction() { // Line 1: Fast operation const array = Array(10000).fill(0); // Line 2: Slow operation - this line will show high samples const sorted = array.map(x => Math.random()).sort(); // Line 3: Another slow operation const filtered = sorted.filter(x => x > 0.5); // Line 4: Fast operation return filtered.length; } // Run the function repeatedly during profiling async function runWorkload() { const results = []; for (let i = 0; i < 1000; i++) { results.push(complexFunction()); } return results; } lineLevelProfiling(); ``` -------------------------------- ### Time Profiler - Profile Collection API Source: https://context7.com/google/pprof-nodejs/llms.txt This API allows you to collect CPU wall-time profile data over a specified duration. It captures function call stacks and execution patterns, returning a profile object that can be encoded to the pprof format. ```APIDOC ## Time Profiler - Profile Collection ### Description Collects CPU wall-time profile data over a specified duration, capturing function call stacks and execution patterns. Returns a profile object that can be encoded to pprof format. ### Method `pprof.time.profile(options)` ### Parameters #### Query Parameters - **durationMillis** (number) - Required - The duration in milliseconds to collect the profile. - **intervalMicros** (number) - Optional - The sampling interval in microseconds. Defaults to 1000. - **lineNumbers** (boolean) - Optional - If true, aggregates at the line number level. Defaults to false (function level aggregation). ### Request Example ```javascript const pprof = require('pprof'); const fs = require('fs').promises; async function collectTimeProfile() { try { const profile = await pprof.time.profile({ durationMillis: 10000, intervalMicros: 1000, lineNumbers: false }); const buf = await pprof.encode(profile); await fs.writeFile('cpu-profile.pb.gz', buf); console.log('Profile saved to cpu-profile.pb.gz'); } catch (err) { console.error('Profiling error:', err); } } collectTimeProfile(); ``` ### Response #### Success Response (Object) - **profile** (Object) - The collected profile object. #### Response Example ```json { "profile": { /* pprof profile object structure */ } } ``` ``` -------------------------------- ### Fix Linting Issues (npm) Source: https://github.com/google/pprof-nodejs/blob/main/CONTRIBUTING.md Lints the code and attempts to automatically fix any style issues using npm. This helps maintain code consistency. ```sh npm run fix ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.