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