Skip to main content

Inspector

The node:inspector module provides an API for interacting with the V8 inspector.

Stability

Stable (Stability: 2)

Import

import * as inspector from 'node:inspector/promises';
const inspector = require('node:inspector/promises');
Or use the callback API:
import * as inspector from 'node:inspector';
const inspector = require('node:inspector');

Promises API

Class: inspector.Session

Used for dispatching messages to the V8 inspector backend.

new inspector.Session()

Create a new inspector session. Must call session.connect() before dispatching messages. When using Session, console output is not released unless you run Runtime.DiscardConsoleEntries.

Event: ‘inspectorNotification’

Emitted when any notification from V8 Inspector is received. Parameters:
  • - The notification message object
session.on('inspectorNotification', (message) => console.log(message.method));

Event: <inspector-protocol-method>

Emitted when a specific inspector notification is received.
session.on('Debugger.paused', ({ params }) => {
  console.log(params.hitBreakpoints);
});

session.connect()

Connects the session to the inspector backend.

session.connectToMainThread()

Connects to the main thread inspector backend. Only works from Worker threads.

session.disconnect()

Immediately closes the session. Pending callbacks receive errors. Reconnecting requires calling connect() again.

session.post(method[, params])

Posts a message to the inspector backend. Parameters:
  • method - Inspector protocol method
  • params - Method parameters
Returns: - Resolves with result or rejects with error
import { Session } from 'node:inspector/promises';
const session = new Session();
session.connect();
const result = await session.post('Runtime.evaluate', { expression: '2 + 2' });
console.log(result);
// Output: { result: { type: 'number', value: 4, description: '4' } }

Example: CPU Profiler

import { Session } from 'node:inspector/promises';
import fs from 'node:fs';

const session = new Session();
session.connect();

await session.post('Profiler.enable');
await session.post('Profiler.start');
// Invoke business logic under measurement here...

const { profile } = await session.post('Profiler.stop');

// Write profile to disk
fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));

Example: Heap Profiler

import { Session } from 'node:inspector/promises';
import fs from 'node:fs';

const session = new Session();
const fd = fs.openSync('profile.heapsnapshot', 'w');

session.connect();

session.on('HeapProfiler.addHeapSnapshotChunk', (m) => {
  fs.writeSync(fd, m.params.chunk);
});

const result = await session.post('HeapProfiler.takeHeapSnapshot', null);
console.log('HeapProfiler.takeHeapSnapshot done:', result);
session.disconnect();
fs.closeSync(fd);

Callback API

Class: inspector.Session

Same as Promises API but uses callbacks.

session.post(method[, params][, callback])

Posts a message with optional callback. Parameters:
  • method - Inspector protocol method
  • params - Method parameters
  • callback - Called with (error, result)
session.post('Runtime.evaluate', { expression: '2 + 2' },
  (error, { result }) => console.log(result));
// Output: { type: 'number', value: 4, description: '4' }

Common Objects

inspector.close()

Attempts to close all connections and deactivate the inspector.

inspector.console

Object to send messages to the remote inspector console.
require('node:inspector').console.log('a message');
The inspector console does not have API parity with Node.js console.

inspector.open([port[, host[, wait]]])

Activate inspector programmatically. Parameters:
  • port - Port to listen on (default: CLI value)
  • host - Host to listen on (default: CLI value)
  • wait - Block until client connects (default: false)
Returns: - Calls inspector.close() on disposal Equivalent to node --inspect=[[host:]port].

inspector.url()

Returns: - URL of the active inspector or undefined
$ node --inspect -p 'inspector.url()'
Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34

inspector.waitForDebugger()

Blocks until a client sends the Runtime.runIfWaitingForDebugger command. Throws if there is no active inspector.

Integration with DevTools

The inspector module provides APIs to integrate with devtools supporting Chrome DevTools Protocol.

Network Inspection

Requires --experimental-network-inspection flag.

inspector.Network.requestWillBeSent([params])

Broadcasts that the application is about to send an HTTP request. Parameters:
  • params - Request details

inspector.Network.responseReceived([params])

Broadcasts that HTTP response is available. Parameters:
  • params - Response details

inspector.Network.loadingFinished([params])

Broadcasts that HTTP request has finished loading. Parameters:
  • params - Loading details

inspector.Network.loadingFailed([params])

Broadcasts that HTTP request has failed. Parameters:
  • params - Error details

inspector.Network.dataReceived([params])

Broadcasts data received event or buffers data. Parameters:
  • params - Data details
Enables Network.getResponseBody command.

inspector.Network.dataSent([params])

Enables Network.getRequestPostData command. Parameters:
  • params - Data details

inspector.Network.webSocketCreated([params])

Broadcasts WebSocket connection initiation. Parameters:
  • params - WebSocket details

inspector.Network.webSocketHandshakeResponseReceived([params])

Broadcasts WebSocket handshake response received. Parameters:
  • params - Handshake details

inspector.Network.webSocketClosed([params])

Broadcasts WebSocket connection closed. Parameters:
  • params - Close details

Resource Management

Requires --experimental-inspector-network-resource flag.

inspector.NetworkResources.put(url, content)

Provide resource content for CDP loadNetworkResource requests. Parameters:
  • url - Resource URL
  • content - Resource content
Useful for serving source maps to DevTools frontends.
const inspector = require('node:inspector');
const mapUrl = 'http://localhost:3000/dist/app.js.map';
const distAppJsMap = await fetch(mapUrl).then((res) => res.text());
inspector.NetworkResources.put(mapUrl, distAppJsMap);

Storage Inspection

Requires --experimental-storage-inspection flag.

inspector.DOMStorage.domStorageItemAdded(params)

Broadcasts that a new item was added to storage. Parameters:
  • params
    • storageId
      • securityOrigin
      • storageKey
      • isLocalStorage
    • key
    • newValue

inspector.DOMStorage.domStorageItemRemoved(params)

Broadcasts that an item was removed from storage.

inspector.DOMStorage.domStorageItemUpdated(params)

Broadcasts that a storage item was updated.

inspector.DOMStorage.domStorageItemsCleared(params)

Broadcasts that all items were cleared from storage.

inspector.DOMStorage.registerStorage(params)

Register storage for inspection. Parameters:
  • params
    • isLocalStorage
    • storageMap

Support of Breakpoints

Avoid setting breakpoints with same-thread inspector.Session. Use session.connectToMainThread() from Worker threads or connect via WebSocket instead.