• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Inspector
2
3<!--introduced_in=v8.0.0-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/inspector.js -->
8
9The `inspector` module provides an API for interacting with the V8 inspector.
10
11It can be accessed using:
12
13```js
14const inspector = require('inspector');
15```
16
17## `inspector.close()`
18
19Deactivate the inspector. Blocks until there are no active connections.
20
21## `inspector.console`
22
23* {Object} An object to send messages to the remote inspector console.
24
25```js
26require('inspector').console.log('a message');
27```
28
29The inspector console does not have API parity with Node.js
30console.
31
32## `inspector.open([port[, host[, wait]]])`
33
34* `port` {number} Port to listen on for inspector connections. Optional.
35  **Default:** what was specified on the CLI.
36* `host` {string} Host to listen on for inspector connections. Optional.
37  **Default:** what was specified on the CLI.
38* `wait` {boolean} Block until a client has connected. Optional.
39  **Default:** `false`.
40
41Activate inspector on host and port. Equivalent to `node
42--inspect=[[host:]port]`, but can be done programmatically after node has
43started.
44
45If wait is `true`, will block until a client has connected to the inspect port
46and flow control has been passed to the debugger client.
47
48See the [security warning](cli.md#inspector_security) regarding the `host`
49parameter usage.
50
51## `inspector.url()`
52
53* Returns: {string|undefined}
54
55Return the URL of the active inspector, or `undefined` if there is none.
56
57```console
58$ node --inspect -p 'inspector.url()'
59Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
60For help see https://nodejs.org/en/docs/inspector
61ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
62
63$ node --inspect=localhost:3000 -p 'inspector.url()'
64Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
65For help see https://nodejs.org/en/docs/inspector
66ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
67
68$ node -p 'inspector.url()'
69undefined
70```
71
72## `inspector.waitForDebugger()`
73<!-- YAML
74added: v12.7.0
75-->
76
77Blocks until a client (existing or connected later) has sent
78`Runtime.runIfWaitingForDebugger` command.
79
80An exception will be thrown if there is no active inspector.
81
82## Class: `inspector.Session`
83
84* Extends: {EventEmitter}
85
86The `inspector.Session` is used for dispatching messages to the V8 inspector
87back-end and receiving message responses and notifications.
88
89### `new inspector.Session()`
90<!-- YAML
91added: v8.0.0
92-->
93
94Create a new instance of the `inspector.Session` class. The inspector session
95needs to be connected through [`session.connect()`][] before the messages
96can be dispatched to the inspector backend.
97
98### Event: `'inspectorNotification'`
99<!-- YAML
100added: v8.0.0
101-->
102
103* {Object} The notification message object
104
105Emitted when any notification from the V8 Inspector is received.
106
107```js
108session.on('inspectorNotification', (message) => console.log(message.method));
109// Debugger.paused
110// Debugger.resumed
111```
112
113It is also possible to subscribe only to notifications with specific method:
114
115### Event: `<inspector-protocol-method>`;
116<!-- YAML
117added: v8.0.0
118-->
119
120* {Object} The notification message object
121
122Emitted when an inspector notification is received that has its method field set
123to the `<inspector-protocol-method>` value.
124
125The following snippet installs a listener on the [`'Debugger.paused'`][]
126event, and prints the reason for program suspension whenever program
127execution is suspended (through breakpoints, for example):
128
129```js
130session.on('Debugger.paused', ({ params }) => {
131  console.log(params.hitBreakpoints);
132});
133// [ '/the/file/that/has/the/breakpoint.js:11:0' ]
134```
135
136### `session.connect()`
137<!-- YAML
138added: v8.0.0
139-->
140
141Connects a session to the inspector back-end.
142
143### `session.connectToMainThread()`
144<!-- YAML
145added: v12.11.0
146-->
147
148Connects a session to the main thread inspector back-end. An exception will
149be thrown if this API was not called on a Worker thread.
150
151### `session.disconnect()`
152<!-- YAML
153added: v8.0.0
154-->
155
156Immediately close the session. All pending message callbacks will be called
157with an error. [`session.connect()`][] will need to be called to be able to send
158messages again. Reconnected session will lose all inspector state, such as
159enabled agents or configured breakpoints.
160
161### `session.post(method[, params][, callback])`
162<!-- YAML
163added: v8.0.0
164-->
165
166* `method` {string}
167* `params` {Object}
168* `callback` {Function}
169
170Posts a message to the inspector back-end. `callback` will be notified when
171a response is received. `callback` is a function that accepts two optional
172arguments: error and message-specific result.
173
174```js
175session.post('Runtime.evaluate', { expression: '2 + 2' },
176             (error, { result }) => console.log(result));
177// Output: { type: 'number', value: 4, description: '4' }
178```
179
180The latest version of the V8 inspector protocol is published on the
181[Chrome DevTools Protocol Viewer][].
182
183Node.js inspector supports all the Chrome DevTools Protocol domains declared
184by V8. Chrome DevTools Protocol domain provides an interface for interacting
185with one of the runtime agents used to inspect the application state and listen
186to the run-time events.
187
188## Example usage
189
190Apart from the debugger, various V8 Profilers are available through the DevTools
191protocol.
192
193### CPU profiler
194
195Here's an example showing how to use the [CPU Profiler][]:
196
197```js
198const inspector = require('inspector');
199const fs = require('fs');
200const session = new inspector.Session();
201session.connect();
202
203session.post('Profiler.enable', () => {
204  session.post('Profiler.start', () => {
205    // Invoke business logic under measurement here...
206
207    // some time later...
208    session.post('Profiler.stop', (err, { profile }) => {
209      // Write profile to disk, upload, etc.
210      if (!err) {
211        fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));
212      }
213    });
214  });
215});
216```
217
218### Heap profiler
219
220Here's an example showing how to use the [Heap Profiler][]:
221
222```js
223const inspector = require('inspector');
224const fs = require('fs');
225const session = new inspector.Session();
226
227const fd = fs.openSync('profile.heapsnapshot', 'w');
228
229session.connect();
230
231session.on('HeapProfiler.addHeapSnapshotChunk', (m) => {
232  fs.writeSync(fd, m.params.chunk);
233});
234
235session.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => {
236  console.log('HeapProfiler.takeHeapSnapshot done:', err, r);
237  session.disconnect();
238  fs.closeSync(fd);
239});
240```
241
242[CPU Profiler]: https://chromedevtools.github.io/devtools-protocol/v8/Profiler
243[Chrome DevTools Protocol Viewer]: https://chromedevtools.github.io/devtools-protocol/v8/
244[Heap Profiler]: https://chromedevtools.github.io/devtools-protocol/v8/HeapProfiler
245[`'Debugger.paused'`]: https://chromedevtools.github.io/devtools-protocol/v8/Debugger#event-paused
246[`session.connect()`]: #inspector_session_connect
247