0
0
NodejsHow-ToBeginner · 4 min read

How to Profile Node.js Application for Performance Analysis

To profile a Node.js application, run it with the --inspect or --inspect-brk flag and connect Chrome DevTools to analyze CPU and memory usage. Alternatively, use the built-in --prof flag to generate a V8 profiling log for detailed performance insights.
📐

Syntax

Use these commands to start profiling your Node.js app:

  • node --inspect app.js: Starts the app with the debugger enabled for live profiling.
  • node --inspect-brk app.js: Starts the app and pauses on the first line to attach debugger before running.
  • node --prof app.js: Runs the app and generates a V8 CPU profile log file for offline analysis.

Each flag enables different profiling methods to help analyze CPU and memory usage.

bash
node --inspect app.js
node --inspect-brk app.js
node --prof app.js
💻

Example

This example shows how to start a Node.js app with the inspector and connect Chrome DevTools for profiling.

javascript
const http = require('http');

const server = http.createServer((req, res) => {
  // Simulate CPU work
  let count = 0;
  for (let i = 0; i < 1e7; i++) {
    count += i;
  }
  res.end('Count: ' + count);
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when profiling Node.js apps include:

  • Not using --inspect or --inspect-brk flags, so DevTools cannot connect.
  • Forgetting to open chrome://inspect in Chrome to attach the debugger.
  • Ignoring the need to generate and process the --prof log with node --prof-process.
  • Profiling in production without understanding overhead, which can slow the app.

Always profile in a controlled environment and follow the correct steps to get meaningful data.

bash
/* Wrong: Running app normally won't allow profiling */
node app.js

/* Right: Start with inspector for profiling */
node --inspect app.js
📊

Quick Reference

CommandPurpose
node --inspect app.jsStart app with debugger for live profiling
node --inspect-brk app.jsStart app paused for debugger attachment
node --prof app.jsGenerate V8 CPU profile log
node --prof-process isolate-0x*.logProcess V8 log into readable report
chrome://inspectOpen Chrome DevTools to connect to Node.js

Key Takeaways

Use --inspect or --inspect-brk flags to enable live profiling with Chrome DevTools.
Use --prof to generate detailed CPU profiling logs for offline analysis.
Always attach Chrome DevTools via chrome://inspect to view profiling data.
Avoid profiling in production without understanding performance impact.
Process V8 logs with node --prof-process to get human-readable reports.