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)
| API | Use |
new inspector.Session() | In-process control |
session.connect() | Attach |
session.post(method, params, cb) | Send command |
| Step | Detail |
Run with --inspect | Exposes WebSocket on 9229 |
Open chrome://inspect | Auto-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)
| Method | Use |
Profiler.enable | Required 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)
| Method | Use |
HeapProfiler.enable | Required |
HeapProfiler.takeHeapSnapshot | Stream chunks via HeapProfiler.addHeapSnapshotChunk event |
HeapProfiler.startSampling | Allocation 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.
| Tool | Use |
| Chrome Performance tab | Visualize CPU profile |
| speedscope | Open .cpuprofile in browser |
| 0x | Generate flamegraph |