Capture Node.js CPU Profiles Using CLI Flags
Identifying performance bottlenecks in Node.js applications is crucial for maintaining fast and efficient services. This article provides a straightforward guide on how to capture CPU profiles of a running Node.js process using built-in command-line interface (CLI) flags and explains how to inspect the resulting profile files to locate slow-running code.
Capturing the CPU Profile
Node.js features a built-in V8 profiler that can be activated at
startup using CLI flags. To start your application and automatically
collect CPU profile data, use the --cpu-prof flag:
node --cpu-prof app.jsOnce the application terminates cleanly or is stopped (for example,
by pressing Ctrl+C), Node.js will write a file with a
.cpuprofile extension to your current working
directory.
Customizing the Profile Output
You can customize the output behavior of the profiler using additional command-line flags:
- Specify directory: Use
--cpu-prof-dirto define where the profile file should be saved. - Specify filename: Use
--cpu-prof-nameto set a custom name for the generated profile file. - Adjust sampling interval: Use
--cpu-prof-intervalto change the sampling interval in microseconds (the default is 1000 microseconds).
For example, to save a profile named
my-profile.cpuprofile in a folder named
profiles, run:
node --cpu-prof --cpu-prof-dir=./profiles --cpu-prof-name=my-profile.cpuprofile app.jsInspecting the CPU Profile
The generated .cpuprofile file is a JSON document
containing execution timing data. To view and analyze this data in a
readable graphical format, you can use Chrome DevTools or Visual Studio
Code.
Method 1: Using Google Chrome DevTools
- Open Google Chrome and navigate to
chrome://inspect. - Click on the Open dedicated DevTools for Node link.
- Select the Profiler tab in the DevTools window.
- Click the Load button in the left-hand sidebar.
- Select and open your generated
.cpuprofilefile.
Once loaded, you can switch between three visualization views: * Chart: A flame graph displaying the call stack over time. * Heavy (Bottom Up): Grouped by functions, showing which functions consumed the most CPU time directly. * Tree (Top Down): A hierarchical view starting from the entry points of your code.
Method 2: Using Visual Studio Code
- Open Visual Studio Code.
- Drag and drop the
.cpuprofilefile directly into the VS Code editor window. - VS Code will automatically render the profile using its built-in visualization tool, allowing you to search for specific functions and analyze execution times directly inside your IDE.