Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

V8 Inspector From Node

| Comments

The inspector module provides an API that makes it easy to interact with the V8 inspector.

One can easily open a inspector like:

1
2
3
4
5
6
7
8
9
10
11
12
13
const inspector = require("inspector");

inspector.open(); // <- inspector.open([port[, host[, wait]]])

/*
Debugger listening on ws://127.0.0.1:9229/ab01a630-90ad-4c87-91c9-a665632c1d8b
For help see https://nodejs.org/en/docs/inspector
*/

inspector.url();
// 'ws://127.0.0.1:9229/ab01a630-90ad-4c87-91c9-a665632c1d8b'

inspector.console.log("This should be visible on the debugger console");

But, most of times we would want to wait until the debugger is connected to our process, that's where inspector.waitForDebugger() will be useful, here is a quick example.

1
2
3
4
5
6
// foo.js
(() => {
    const inspector = require("inspector");
    inspector.open();
    inspector.waitForDebugger();
})();
1
2
3
4
5
6
7
8
9
> node foo.js

^ This would make the process wait till the debugger is connected.
/*
  Debugger listening on ws://127.0.0.1:9229/b4b0e48d-2e4c-4cde-8177-6924c662aef4
  For help, see: https://nodejs.org/en/docs/inspector
  Debugger attached.
  Waiting for the debugger to disconnect...
  */

Dispatching and receiving message responses and notifications is possible with the session API:

1
2
3
4
5
6
7
8
9
10
11
12
const inspector = require("inspector");
inspector.open();
inspector.waitForDebugger();

const session = new inspsector.Session();
session.on("inspectorNotification", (message) => console.log(message.method));
// Debugger.paused
// Debugger.resumed

session.post("Runtime.evaluate", { expression: "5 + 4" }, (error, { result }) =>
    console.log(result)
); // 9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> new inspector.Session()
Session {
  domain:
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] },
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  [Symbol(connectionProperty)]: null,
  [Symbol(nextId)]: 1,
  [Symbol(messageCallbacks)]: Map {} }

session.on(<inspector-protocol-method>) where the methods are from devtools-protocol.

P.S: This is an experimental API with Stability of 1 meaning is not subject to Semantic Versioning rules. Non-backward compatible changes or removal may occur in any future release. Use of the feature is not recommended in production environments.

Comments