Node.js v20.20.6 文档


检查器#>

【Inspector】

源代码: lib/inspector.js

node:inspector 模块提供了一个用于与 V8 检查器交互的 API。

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

可以使用以下方式访问它:

【It can be accessed using:】

import * as inspector from 'node:inspector/promises';const inspector = require('node:inspector/promises');

或者

【or】

import * as inspector from 'node:inspector';const inspector = require('node:inspector');

Promise API#>

【Promises API】

稳定性: 1 - 实验性

类:inspector.Session#>

【Class: inspector.Session

inspector.Session 用于向 V8 检查器后端发送消息,并接收消息响应和通知。

【The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications.】

new inspector.Session()#>

创建一个 inspector.Session 类的新实例。Inspector 会话需要先通过 session.connect() 连接,然后才能将消息发送到 inspector 后端。

【Create a new instance of the inspector.Session class. The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend.】

在使用 Session 时,控制台 API 输出的对象不会被释放,除非我们手动执行 Runtime.DiscardConsoleEntries 命令。

【When using Session, the object outputted by the console API will not be released, unless we performed manually Runtime.DiscardConsoleEntries command.】

事件:'inspectorNotification'#>

【Event: 'inspectorNotification'

当接收到来自 V8 检查器的任何通知时触发。

【Emitted when any notification from the V8 Inspector is received.】

session.on('inspectorNotification', (message) => console.log(message.method));
// Debugger.paused
// Debugger.resumed 

注意 不建议在同一线程会话中使用断点,请参阅 断点支持

也可以只订阅特定方法的通知:

【It is also possible to subscribe only to notifications with specific method:】

事件:<inspector-protocol-method>#>

【Event: <inspector-protocol-method>;】

当收到方法字段设置为 <inspector-protocol-method> 的检查器通知时触发。

【Emitted when an inspector notification is received that has its method field set to the <inspector-protocol-method> value.】

以下代码片段在 'Debugger.paused' 事件上安装了一个监听器,并在程序执行被暂停时(例如通过断点)打印程序暂停的原因:

【The following snippet installs a listener on the 'Debugger.paused' event, and prints the reason for program suspension whenever program execution is suspended (through breakpoints, for example):】

session.on('Debugger.paused', ({ params }) => {
  console.log(params.hitBreakpoints);
});
// [ '/the/file/that/has/the/breakpoint.js:11:0' ] 

注意 不建议在同一线程会话中使用断点,请参阅 断点支持

session.connect()#>

将会话连接到检查器后端。

【Connects a session to the inspector back-end.】

session.connectToMainThread()#>

将会话连接到主线程检查器后端。如果此 API 未在 Worker 线程上调用,将会抛出异常。

【Connects a session to the main thread inspector back-end. An exception will be thrown if this API was not called on a Worker thread.】

session.disconnect()#>

立即关闭会话。所有待处理的消息回调将会收到错误。需要调用 session.connect() 才能再次发送消息。重新连接的会话将丢失所有检查器状态,例如已启用的代理或已配置的断点。

【Immediately close the session. All pending message callbacks will be called with an error. session.connect() will need to be called to be able to send messages again. Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints.】

session.post(method[, params])#>

向检查器后端发布消息。

【Posts a message to the inspector back-end.】

import { Session } from 'node:inspector/promises';
try {
  const session = new Session();
  session.connect();
  const result = await session.post('Runtime.evaluate', { expression: '2 + 2' });
  console.log(result);
} catch (error) {
  console.error(error);
}
// Output: { result: { type: 'number', value: 4, description: '4' } } 

V8 检查器协议的最新版本已发布在 Chrome 开发者工具协议查看器

【The latest version of the V8 inspector protocol is published on the Chrome DevTools Protocol Viewer.】

Node.js 调试器支持 V8 声明的所有 Chrome DevTools 协议域。Chrome DevTools 协议域提供了与运行时代理交互的接口,用于检查应用状态并监听运行时事件。

【Node.js inspector supports all the Chrome DevTools Protocol domains declared by V8. Chrome DevTools Protocol domain provides an interface for interacting with one of the runtime agents used to inspect the application state and listen to the run-time events.】

用法示例#>

【Example usage】

除了调试器之外,还可以通过 DevTools 协议使用各种 V8 分析器。

【Apart from the debugger, various V8 Profilers are available through the DevTools protocol.】

CPU 分析器#>

【CPU profiler】

下面是一个展示如何使用 CPU 分析器 的示例:

【Here's an example showing how to use the 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...

// some time later...
const { profile } = await session.post('Profiler.stop');

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

堆分析器#>

【Heap profiler】

下面是一个展示如何使用 堆分析器 的示例:

【Here's an example showing how to use the 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】

类:inspector.Session#>

【Class: inspector.Session

inspector.Session 用于向 V8 检查器后端发送消息,并接收消息响应和通知。

【The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications.】

new inspector.Session()#>

创建一个 inspector.Session 类的新实例。Inspector 会话需要先通过 session.connect() 连接,然后才能将消息发送到 inspector 后端。

【Create a new instance of the inspector.Session class. The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend.】

在使用 Session 时,控制台 API 输出的对象不会被释放,除非我们手动执行 Runtime.DiscardConsoleEntries 命令。

【When using Session, the object outputted by the console API will not be released, unless we performed manually Runtime.DiscardConsoleEntries command.】

事件:'inspectorNotification'#>

【Event: 'inspectorNotification'

当接收到来自 V8 检查器的任何通知时触发。

【Emitted when any notification from the V8 Inspector is received.】

session.on('inspectorNotification', (message) => console.log(message.method));
// Debugger.paused
// Debugger.resumed 

注意 不建议在同一线程会话中使用断点,请参阅 断点支持

也可以只订阅特定方法的通知:

【It is also possible to subscribe only to notifications with specific method:】

事件:<inspector-protocol-method>#>

【Event: <inspector-protocol-method>;】

当收到方法字段设置为 <inspector-protocol-method> 的检查器通知时触发。

【Emitted when an inspector notification is received that has its method field set to the <inspector-protocol-method> value.】

以下代码片段在 'Debugger.paused' 事件上安装了一个监听器,并在程序执行被暂停时(例如通过断点)打印程序暂停的原因:

【The following snippet installs a listener on the 'Debugger.paused' event, and prints the reason for program suspension whenever program execution is suspended (through breakpoints, for example):】

session.on('Debugger.paused', ({ params }) => {
  console.log(params.hitBreakpoints);
});
// [ '/the/file/that/has/the/breakpoint.js:11:0' ] 

注意 不建议在同一线程会话中使用断点,请参阅 断点支持

session.connect()#>

将会话连接到检查器后端。

【Connects a session to the inspector back-end.】

session.connectToMainThread()#>

将会话连接到主线程检查器后端。如果此 API 未在 Worker 线程上调用,将会抛出异常。

【Connects a session to the main thread inspector back-end. An exception will be thrown if this API was not called on a Worker thread.】

session.disconnect()#>

立即关闭会话。所有待处理的消息回调将会收到错误。需要调用 session.connect() 才能再次发送消息。重新连接的会话将丢失所有检查器状态,例如已启用的代理或已配置的断点。

【Immediately close the session. All pending message callbacks will be called with an error. session.connect() will need to be called to be able to send messages again. Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints.】

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

向检查器后端发送消息。当接收到响应时,将通知 callbackcallback 是一个函数,它接受两个可选参数:错误和消息特定的结果。

【Posts a message to the inspector back-end. callback will be notified when a response is received. callback is a function that accepts two optional arguments: error and message-specific result.】

session.post('Runtime.evaluate', { expression: '2 + 2' },
             (error, { result }) => console.log(result));
// Output: { type: 'number', value: 4, description: '4' } 

V8 检查器协议的最新版本已发布在 Chrome 开发者工具协议查看器

【The latest version of the V8 inspector protocol is published on the Chrome DevTools Protocol Viewer.】

Node.js 调试器支持 V8 声明的所有 Chrome DevTools 协议域。Chrome DevTools 协议域提供了与运行时代理交互的接口,用于检查应用状态并监听运行时事件。

【Node.js inspector supports all the Chrome DevTools Protocol domains declared by V8. Chrome DevTools Protocol domain provides an interface for interacting with one of the runtime agents used to inspect the application state and listen to the run-time events.】

当向 V8 发送 HeapProfiler.takeHeapSnapshotHeapProfiler.stopTrackingHeapObjects 命令时,不能将 reportProgress 设置为 true

【You can not set reportProgress to true when sending a HeapProfiler.takeHeapSnapshot or HeapProfiler.stopTrackingHeapObjects command to V8.】

用法示例#>

【Example usage】

除了调试器之外,还可以通过 DevTools 协议使用各种 V8 分析器。

【Apart from the debugger, various V8 Profilers are available through the DevTools protocol.】

CPU 分析器#>

【CPU profiler】

下面是一个展示如何使用 CPU 分析器 的示例:

【Here's an example showing how to use the CPU Profiler:】

const inspector = require('node:inspector');
const fs = require('node:fs');
const session = new inspector.Session();
session.connect();

session.post('Profiler.enable', () => {
  session.post('Profiler.start', () => {
    // Invoke business logic under measurement here...

    // some time later...
    session.post('Profiler.stop', (err, { profile }) => {
      // Write profile to disk, upload, etc.
      if (!err) {
        fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));
      }
    });
  });
}); 

堆分析器#>

【Heap profiler】

下面是一个展示如何使用 堆分析器 的示例:

【Here's an example showing how to use the Heap Profiler:】

const inspector = require('node:inspector');
const fs = require('node:fs');
const session = new inspector.Session();

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

session.connect();

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

session.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => {
  console.log('HeapProfiler.takeHeapSnapshot done:', err, r);
  session.disconnect();
  fs.closeSync(fd);
}); 

常见对象#>

【Common Objects】

inspector.close()#>

尝试关闭所有剩余的连接,阻塞事件循环直到所有连接关闭。一旦所有连接关闭,就停用检查器。

【Attempts to close all remaining connections, blocking the event loop until all are closed. Once all connections are closed, deactivates the inspector.】

inspector.console#>

  • <Object> 一个用于向远程检查器控制台发送消息的对象。
require('node:inspector').console.log('a message'); 

检查器控制台与 Node.js 控制台的 API 不完全一致。

【The inspector console does not have API parity with Node.js console.】

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

  • port <number> 用于监听调试器连接的端口。可选。 默认值: 命令行中指定的值。
  • host <string> 用于监听调试器连接的主机。可选。 默认值: 命令行中指定的值。
  • wait <boolean> 阻塞直到客户端连接。可选。 默认值: false
  • 返回值: <Disposable> 一个 Disposable,会调用 inspector.close()

在主机和端口上激活调试器。等同于 node --inspect=[[host:]port],但可以在 Node 启动后通过编程方式完成。

【Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programmatically after node has started.】

如果 wait 为 true,将阻塞直到有客户端连接到调试端口并且流量控制已传递给调试客户端。

【If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client.】

请参阅 安全警告 关于 host 参数的使用。

【See the security warning regarding the host parameter usage.】

inspector.url()#>

返回活动检查器的 URL,如果没有则返回 undefined

【Return the URL of the active inspector, or undefined if there is none.】

$ node --inspect -p 'inspector.url()'
Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
For help, see: https://nodejs.cn/docs/inspector
ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34

$ node --inspect=localhost:3000 -p 'inspector.url()'
Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
For help, see: https://nodejs.cn/docs/inspector
ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a

$ node -p 'inspector.url()'
undefined 

inspector.waitForDebugger()#>

阻塞,直到客户端(现有的或稍后连接的)发送 Runtime.runIfWaitingForDebugger 命令。

【Blocks until a client (existing or connected later) has sent Runtime.runIfWaitingForDebugger command.】

如果没有活动的检查器,则将会抛出异常。

【An exception will be thrown if there is no active inspector.】

与 DevTools 集成#>

【Integration with DevTools】

node:inspector 模块提供了一个 API,用于与支持 Chrome DevTools 协议的开发工具集成。连接到运行中 Node.js 实例的 DevTools 前端可以捕获实例发出的协议事件,并相应地显示它们以便调试。以下方法会向所有已连接的前端广播协议事件。传递给方法的 params 可以是可选的,这取决于协议。

【The node:inspector module provides an API for integrating with devtools that support Chrome DevTools Protocol. DevTools frontends connected to a running Node.js instance can capture protocol events emitted from the instance and display them accordingly to facilitate debugging. The following methods broadcast a protocol event to all connected frontends. The params passed to the methods can be optional, depending on the protocol.】

// The `Network.requestWillBeSent` event will be fired.
inspector.Network.requestWillBeSent({
  requestId: 'request-id-1',
  timestamp: Date.now() / 1000,
  wallTime: Date.now(),
  request: {
    url: 'https://nodejs.cn/en',
    method: 'GET',
  },
}); 

inspector.Network.requestWillBeSent([params])#>

稳定性: 1 - 实验性

此功能仅在启用 --experimental-network-inspection 标志时可用。

【This feature is only available with the --experimental-network-inspection flag enabled.】

Network.requestWillBeSent 事件广播给已连接的前端。此事件表示应用即将发送 HTTP 请求。

【Broadcasts the Network.requestWillBeSent event to connected frontends. This event indicates that the application is about to send an HTTP request.】

inspector.Network.responseReceived([params])#>

稳定性: 1 - 实验性

此功能仅在启用 --experimental-network-inspection 标志时可用。

【This feature is only available with the --experimental-network-inspection flag enabled.】

Network.responseReceived 事件广播到已连接的前端。此事件表示 HTTP 响应已可用。

【Broadcasts the Network.responseReceived event to connected frontends. This event indicates that HTTP response is available.】

inspector.Network.loadingFinished([params])#>

稳定性: 1 - 实验性

此功能仅在启用 --experimental-network-inspection 标志时可用。

【This feature is only available with the --experimental-network-inspection flag enabled.】

向已连接的前端广播 Network.loadingFinished 事件。此事件表示 HTTP 请求已完成加载。

【Broadcasts the Network.loadingFinished event to connected frontends. This event indicates that HTTP request has finished loading.】

inspector.Network.loadingFailed([params])#>

稳定性: 1 - 实验性

此功能仅在启用 --experimental-network-inspection 标志时可用。

【This feature is only available with the --experimental-network-inspection flag enabled.】

向连接的前端广播 Network.loadingFailed 事件。此事件表示 HTTP 请求加载失败。

【Broadcasts the Network.loadingFailed event to connected frontends. This event indicates that HTTP request has failed to load.】

支持断点#>

【Support of breakpoints】

Chrome DevTools 协议 Debugger 允许 inspector.Session 附加到一个程序,并设置断点以逐步执行代码。

【The Chrome DevTools Protocol Debugger domain allows an inspector.Session to attach to a program and set breakpoints to step through the codes.】

然而,应该避免在通过 session.connect() 连接的同线程 inspector.Session 中设置断点,因为被附加并暂停的程序正是调试器本身。相反,可以尝试通过 session.connectToMainThread() 连接到主线程,并在工作线程中设置断点,或者通过 WebSocket 连接到 调试器 程序。

【However, setting breakpoints with a same-thread inspector.Session, which is connected by session.connect(), should be avoided as the program being attached and paused is exactly the debugger itself. Instead, try connect to the main thread by session.connectToMainThread() and set breakpoints in a worker thread, or connect with a Debugger program over WebSocket connection.】

Node.js 中文网 - 粤ICP备13048890号