Skip to main content

Working with Inspector Module

1. Opening Inspector (inspector.open)

Example

import inspector from "node:inspector";
inspector.open(9229, "127.0.0.1", true); // wait for debugger

2. Creating Inspector Session (new inspector.Session)

APIUse
new inspector.Session()In-process control
session.connect()Attach
session.post(method, params, cb)Send command

3. Connecting to Chrome DevTools

StepDetail
Run with --inspectExposes WebSocket on 9229
Open chrome://inspectAuto-discovers local targets
Or use devtools://devtools/bundled/js_app.html?ws=...Direct URL

4. Posting Protocol Messages

Example: Enable profiler

const session = new inspector.Session();
session.connect();
session.post("Profiler.enable");
session.post("Profiler.start");

5. Enabling Profiler (Profiler.enable)

MethodUse
Profiler.enableRequired before start
Profiler.setSamplingIntervalμs between samples

6. Taking CPU Profiles

Example

session.post("Profiler.start");
runWorkload();
session.post("Profiler.stop", (err, { profile }) => {
  fs.writeFileSync("./cpu.cpuprofile", JSON.stringify(profile));
});

7. Taking Heap Snapshots (HeapProfiler)

MethodUse
HeapProfiler.enableRequired
HeapProfiler.takeHeapSnapshotStream chunks via HeapProfiler.addHeapSnapshotChunk event
HeapProfiler.startSamplingAllocation sampling

8. Using Coverage (Profiler.startPreciseCoverage)

Example

session.post("Profiler.startPreciseCoverage", { callCount: true, detailed: true });
runTests();
session.post("Profiler.takePreciseCoverage", (err, { result }) => saveCoverage(result));

9. Debugging Remotely

Warning: Inspector port grants full code execution. Bind to 127.0.0.1 only, or tunnel via SSH.

10. Analyzing Runtime Performance

ToolUse
Chrome Performance tabVisualize CPU profile
speedscopeOpen .cpuprofile in browser
0xGenerate flamegraph

Was this article helpful?