- 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 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
Node.js v22.11.0 文档
- Node.js v22.11.0
- 目录
-
导航
- 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 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- 其他版本
检查器#
¥Inspector
¥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#
¥Stability: 1 - Experimental
类:inspector.Session
#
¥Class: inspector.Session
-
¥Extends: <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
类的新实例。检查器会话需要通过 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
警告 不建议在同线程会话中使用断点,请参阅[断点支持][断点支持]。
¥Breakpoints with same-thread session is not recommended, see support of breakpoints.
也可以只订阅特定方法的通知:
¥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' ]
警告 不建议在同线程会话中使用断点,请参阅[断点支持][断点支持]。
¥Breakpoints with same-thread session is not recommended, see support of breakpoints.
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
-
¥Extends: <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
类的新实例。检查器会话需要通过 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
警告 不建议在同线程会话中使用断点,请参阅[断点支持][断点支持]。
¥Breakpoints with same-thread session is not recommended, see support of breakpoints.
也可以只订阅特定方法的通知:
¥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' ]
警告 不建议在同线程会话中使用断点,请参阅[断点支持][断点支持]。
¥Breakpoints with same-thread session is not recommended, see support of breakpoints.
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])
#
-
method
<string> -
params
<Object> -
callback
<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 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.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
除了调试器之外,还可以通过开发者工具协议使用各种 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
#
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> A 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()
#
-
返回:<string> | <undefined>
¥Returns: <string> | <undefined>
返回活动检查器的网址,如果没有,则返回 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 协议的 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])
#
¥Stability: 1 - Experimental
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])
#
¥Stability: 1 - Experimental
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])
#
¥Stability: 1 - Experimental
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])
#
¥Stability: 1 - Experimental
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.