Node.js v18.20.8 文档


检查器#>

【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:】

const inspector = require('node:inspector'); 

inspector.close()#>

停用检查器。阻塞操作,直到没有活动连接。

【Deactivate the inspector. Blocks until there are no active connections.】

在使用 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.】

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

在主机和端口上激活调试器。等同于 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.】

类: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);
}); 
Node.js 中文网 - 粤ICP备13048890号