Hemanth's Scribes

node

V8 Inspector from Node

Author Photo

Hemanth HM

Thumbnail

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

Opening an Inspector

One can easily open an inspector like:

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");

Waiting for Debugger

Most of the time we would want to wait until the debugger is connected to our process. That’s where inspector.waitForDebugger() will be useful:

// foo.js
(() => {
  const inspector = require("inspector");
  inspector.open();
  inspector.waitForDebugger();
})();
> 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...

Session API

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

const inspector = require("inspector");

inspector.open();
inspector.waitForDebugger();

const session = new inspector.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

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

P.S: This is an experimental API with Stability of 1, meaning it 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.

#node#javascript#debugging#v8
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.