- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
Node.js v20.20.6 文档
- Node.js v20.20.6
- 目录
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- 其他版本
检查器#>
【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】
类:inspector.Session#>
【Class: inspector.Session】
- 继承: <EventEmitter>
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'】
- <Object> 通知消息对象
当接收到来自 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>;】
- <Object> 通知消息对象
当收到方法字段设置为 <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】
- 继承: <EventEmitter>
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'】
- <Object> 通知消息对象
当接收到来自 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>;】
- <Object> 通知消息对象
当收到方法字段设置为 <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])#>
方法<string>参数<Object>回调<Function>
向检查器后端发送消息。当接收到响应时,将通知 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 检查器协议的最新版本已发布在 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.takeHeapSnapshot 或 HeapProfiler.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()#>
- 返回: <string> | <undefined>
返回活动检查器的 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])#>
params<Object>
此功能仅在启用 --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])#>
params<Object>
此功能仅在启用 --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])#>
params<Object>
此功能仅在启用 --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])#>
params<Object>
此功能仅在启用 --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.】