Node.js v20.11.1 文档


检查器#

¥Inspector

稳定性: 2 - 稳定的

¥Stability: 2 - Stable

源代码: 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#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

类: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 类的新实例。检查器会话需要通过 session.connect() 连接才能将消息发送到检查器后端。

¥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,则会抛出异常。

¥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 inspector 协议发布在 Chrome DevTools 协议查看器 上。

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

Node.js 检查器支持 V8 声明的所有 Chrome 开发者工具协议域。Chrome 开发者工具协议域提供了一个接口,用于与用于检查应用状态和监听运行时事件的运行时代理之一进行交互。

¥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

除了调试器之外,还可以通过开发者工具协议使用各种 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 类的新实例。检查器会话需要通过 session.connect() 连接才能将消息发送到检查器后端。

¥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,则会抛出异常。

¥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])#

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

¥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 inspector 协议发布在 Chrome DevTools 协议查看器 上。

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

Node.js 检查器支持 V8 声明的所有 Chrome 开发者工具协议域。Chrome 开发者工具协议域提供了一个接口,用于与用于检查应用状态和监听运行时事件的运行时代理之一进行交互。

¥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

除了调试器之外,还可以通过开发者工具协议使用各种 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> 将消息发送到远程检查器控制台的对象。

    ¥<Object> An object to send messages to the remote inspector console.

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> 监听检查器连接的端口。可选的。默认值:CLI 上指定的内容。

    ¥port <number> Port to listen on for inspector connections. Optional. Default: what was specified on the CLI.

  • host <string> 主机监听检查器连接。可选的。默认值:CLI 上指定的内容。

    ¥host <string> Host to listen on for inspector connections. Optional. Default: what was specified on the CLI.

  • wait <boolean> 在客户端连接之前阻塞。可选的。默认值:false

    ¥wait <boolean> Block until a client has connected. Optional. Default: false.

  • 返回:<Disposable> 调用 inspector.close()

    ¥Returns: <Disposable> that calls 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.

如果等待为 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()#

返回活动检查器的网址,如果没有,则返回 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.