diff --git a/doc/api/inspector.md b/doc/api/inspector.md index 6af8b90aaf6238..f419a4d17bae52 100644 --- a/doc/api/inspector.md +++ b/doc/api/inspector.md @@ -154,10 +154,12 @@ to the run-time events. ## Example usage +Apart from the debugger, various V8 Profilers are available through the DevTools +protocol. + ### CPU Profiler -Apart from the debugger, various V8 Profilers are available through the DevTools -protocol. Here's a simple example showing how to use the [CPU profiler][]: +Here's an example showing how to use the [CPU Profiler][]: ```js const inspector = require('inspector'); @@ -180,8 +182,33 @@ session.post('Profiler.enable', () => { }); ``` +### Heap Profiler + +Here's an example showing how to use the [Heap Profiler][]: + +```js +const inspector = require('inspector'); +const fs = require('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('Runtime.takeHeapSnapshot done:', err, r); + session.disconnect(); + fs.closeSync(fd); +}); +``` + [`'Debugger.paused'`]: https://chromedevtools.github.io/devtools-protocol/v8/Debugger#event-paused [`EventEmitter`]: events.html#events_class_eventemitter [`session.connect()`]: #inspector_session_connect [CPU Profiler]: https://chromedevtools.github.io/devtools-protocol/v8/Profiler [Chrome DevTools Protocol Viewer]: https://chromedevtools.github.io/devtools-protocol/v8/ +[Heap Profiler]: https://chromedevtools.github.io/devtools-protocol/v8/HeapProfiler diff --git a/test/parallel/test-inspector-heapdump.js b/test/parallel/test-inspector-heapdump.js new file mode 100644 index 00000000000000..4520de731fa57d --- /dev/null +++ b/test/parallel/test-inspector-heapdump.js @@ -0,0 +1,30 @@ +'use strict'; +const common = require('../common'); + +common.skipIfInspectorDisabled(); + +// Test that example code in doc/api/inspector.md continues to work with the V8 +// experimental API. + +const assert = require('assert'); +const inspector = require('inspector'); +const session = new inspector.Session(); + +session.connect(); + +const chunks = []; + +session.on('HeapProfiler.addHeapSnapshotChunk', (m) => { + chunks.push(m.params.chunk); +}); + +session.post('HeapProfiler.takeHeapSnapshot', null, common.mustCall((e, r) => { + assert.ifError(e); + assert.deepStrictEqual(r, {}); + session.disconnect(); + + const profile = JSON.parse(chunks.join('')); + assert(profile.snapshot.meta); + assert(profile.snapshot.node_count > 0); + assert(profile.snapshot.edge_count > 0); +}));