|
7 | 7 | The `node:v8` module exposes APIs that are specific to the version of [V8][] |
8 | 8 | built into the Node.js binary. It can be accessed using: |
9 | 9 |
|
10 | | -```js |
| 10 | +```mjs |
| 11 | +import v8 from 'node:v8'; |
| 12 | +``` |
| 13 | + |
| 14 | +```cjs |
11 | 15 | const v8 = require('node:v8'); |
12 | 16 | ``` |
13 | 17 |
|
@@ -92,9 +96,18 @@ terminating the process. |
92 | 96 | Generating a snapshot is a synchronous operation which blocks the event loop |
93 | 97 | for a duration depending on the heap size. |
94 | 98 |
|
| 99 | +```mjs |
| 100 | +// Print heap snapshot to the console |
| 101 | +import { getHeapSnapshot } from 'node:v8'; |
| 102 | +import process from 'node:process'; |
| 103 | +const stream = getHeapSnapshot(); |
| 104 | +stream.pipe(process.stdout); |
| 105 | +``` |
| 106 | + |
95 | 107 | ```js |
96 | 108 | // Print heap snapshot to the console |
97 | 109 | const v8 = require('node:v8'); |
| 110 | +const process = require('node:process'); |
98 | 111 | const stream = v8.getHeapSnapshot(); |
99 | 112 | stream.pipe(process.stdout); |
100 | 113 | ``` |
@@ -467,11 +480,70 @@ The V8 options available for a version of Node.js may be determined by running |
467 | 480 |
|
468 | 481 | Usage: |
469 | 482 |
|
470 | | -```js |
471 | | -// Print GC events to stdout for one minute. |
472 | | -const v8 = require('node:v8'); |
473 | | -v8.setFlagsFromString('--trace_gc'); |
474 | | -setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); |
| 483 | +```mjs |
| 484 | +import { setFlagsFromString } from 'node:v8'; |
| 485 | +import { setInterval } from 'node:timers'; |
| 486 | + |
| 487 | +// setFlagsFromString to trace garbage collection events |
| 488 | +setFlagsFromString('--trace-gc'); |
| 489 | + |
| 490 | +// Trigger GC events by using some memory |
| 491 | +let arrays = []; |
| 492 | +const interval = setInterval(() => { |
| 493 | + for (let i = 0; i < 500; i++) { |
| 494 | + arrays.push(new Array(10000).fill(Math.random())); |
| 495 | + } |
| 496 | + |
| 497 | + if (arrays.length > 5000) { |
| 498 | + arrays = arrays.slice(-1000); |
| 499 | + } |
| 500 | + |
| 501 | + console.log(`\n* Created ${arrays.length} arrays\n`); |
| 502 | +}, 100); |
| 503 | + |
| 504 | +// setFlagsFromString to stop tracing GC events after 1.5 seconds |
| 505 | +setTimeout(() => { |
| 506 | + setFlagsFromString('--notrace-gc'); |
| 507 | + console.log('\nStopped tracing!\n'); |
| 508 | +}, 1500); |
| 509 | + |
| 510 | +// Stop triggering GC events altogether after 2.5 seconds |
| 511 | +setTimeout(() => { |
| 512 | + clearInterval(interval); |
| 513 | +}, 2500); |
| 514 | +``` |
| 515 | + |
| 516 | +```cjs |
| 517 | +const { setFlagsFromString } = require('node:v8'); |
| 518 | +const { setInterval } = require('node:timers'); |
| 519 | + |
| 520 | +// setFlagsFromString to trace garbage collection events |
| 521 | +setFlagsFromString('--trace-gc'); |
| 522 | + |
| 523 | +// Trigger GC events by using some memory |
| 524 | +let arrays = []; |
| 525 | +const interval = setInterval(() => { |
| 526 | + for (let i = 0; i < 500; i++) { |
| 527 | + arrays.push(new Array(10000).fill(Math.random())); |
| 528 | + } |
| 529 | + |
| 530 | + if (arrays.length > 5000) { |
| 531 | + arrays = arrays.slice(-1000); |
| 532 | + } |
| 533 | + |
| 534 | + console.log(`\n* Created ${arrays.length} arrays\n`); |
| 535 | +}, 100); |
| 536 | + |
| 537 | +// setFlagsFromString to stop tracing GC events after 1.5 seconds |
| 538 | +setTimeout(() => { |
| 539 | + console.log('\nStopped tracing!\n'); |
| 540 | + setFlagsFromString('--notrace-gc'); |
| 541 | +}, 1500); |
| 542 | + |
| 543 | +// Stop triggering GC events altogether after 2.5 seconds |
| 544 | +setTimeout(() => { |
| 545 | + clearInterval(interval); |
| 546 | +}, 2500); |
475 | 547 | ``` |
476 | 548 |
|
477 | 549 | ## `v8.stopCoverage()` |
@@ -551,13 +623,37 @@ terminating the process. |
551 | 623 | Generating a snapshot is a synchronous operation which blocks the event loop |
552 | 624 | for a duration depending on the heap size. |
553 | 625 |
|
554 | | -```js |
| 626 | +```mjs |
| 627 | +import { writeHeapSnapshot } from 'node:v8'; |
| 628 | +import { Worker, isMainThread, parentPort } from 'node:worker_threads'; |
| 629 | +import { fileURLToPath } from 'node:url'; |
| 630 | + |
| 631 | +if (isMainThread) { |
| 632 | + const __filename = fileURLToPath(import.meta.url); |
| 633 | + const worker = new Worker(__filename); |
| 634 | + |
| 635 | + worker.once('message', (filename) => { |
| 636 | + console.log(`worker heapdump: ${filename}`); |
| 637 | + // Now get a heapdump for the main thread. |
| 638 | + console.log(`main thread heapdump: ${writeHeapSnapshot()}`); |
| 639 | + }); |
| 640 | + |
| 641 | + // Tell the worker to create a heapdump. |
| 642 | + worker.postMessage('heapdump'); |
| 643 | +} else { |
| 644 | + parentPort.once('message', (message) => { |
| 645 | + if (message === 'heapdump') { |
| 646 | + // Generate a heapdump for the worker |
| 647 | + // and return the filename to the parent. |
| 648 | + parentPort.postMessage(writeHeapSnapshot()); |
| 649 | + } |
| 650 | + }); |
| 651 | +} |
| 652 | +``` |
| 653 | +
|
| 654 | +```cjs |
555 | 655 | const { writeHeapSnapshot } = require('node:v8'); |
556 | | -const { |
557 | | - Worker, |
558 | | - isMainThread, |
559 | | - parentPort, |
560 | | -} = require('node:worker_threads'); |
| 656 | +const { Worker, isMainThread, parentPort } = require('node:worker_threads'); |
561 | 657 |
|
562 | 658 | if (isMainThread) { |
563 | 659 | const worker = new Worker(__filename); |
@@ -903,6 +999,71 @@ const stopHookSet = promiseHooks.createHook({ |
903 | 999 | after, |
904 | 1000 | }); |
905 | 1001 |
|
| 1002 | +// Trigger the hooks by using promises |
| 1003 | +const promiseLog = (word) => Promise.resolve(word).then(console.log); |
| 1004 | +promiseLog('Hello'); |
| 1005 | +promiseLog('World'); |
| 1006 | + |
| 1007 | +// To stop a hook, call the function returned at its creation. |
| 1008 | +stopWatchingInits(); |
| 1009 | +stopWatchingSettleds(); |
| 1010 | +stopWatchingBefores(); |
| 1011 | +stopWatchingAfters(); |
| 1012 | +stopHookSet(); |
| 1013 | +``` |
| 1014 | +
|
| 1015 | +```cjs |
| 1016 | +const { promiseHooks } = require('node:v8'); |
| 1017 | + |
| 1018 | +// There are four lifecycle events produced by promises: |
| 1019 | + |
| 1020 | +// The `init` event represents the creation of a promise. This could be a |
| 1021 | +// direct creation such as with `new Promise(...)` or a continuation such |
| 1022 | +// as `then()` or `catch()`. It also happens whenever an async function is |
| 1023 | +// called or does an `await`. If a continuation promise is created, the |
| 1024 | +// `parent` will be the promise it is a continuation from. |
| 1025 | +function init(promise, parent) { |
| 1026 | + console.log('a promise was created', { promise, parent }); |
| 1027 | +} |
| 1028 | + |
| 1029 | +// The `settled` event happens when a promise receives a resolution or |
| 1030 | +// rejection value. This may happen synchronously such as when using |
| 1031 | +// `Promise.resolve()` on non-promise input. |
| 1032 | +function settled(promise) { |
| 1033 | + console.log('a promise resolved or rejected', { promise }); |
| 1034 | +} |
| 1035 | + |
| 1036 | +// The `before` event runs immediately before a `then()` or `catch()` handler |
| 1037 | +// runs or an `await` resumes execution. |
| 1038 | +function before(promise) { |
| 1039 | + console.log('a promise is about to call a then handler', { promise }); |
| 1040 | +} |
| 1041 | + |
| 1042 | +// The `after` event runs immediately after a `then()` handler runs or when |
| 1043 | +// an `await` begins after resuming from another. |
| 1044 | +function after(promise) { |
| 1045 | + console.log('a promise is done calling a then handler', { promise }); |
| 1046 | +} |
| 1047 | + |
| 1048 | +// Lifecycle hooks may be started and stopped individually |
| 1049 | +const stopWatchingInits = promiseHooks.onInit(init); |
| 1050 | +const stopWatchingSettleds = promiseHooks.onSettled(settled); |
| 1051 | +const stopWatchingBefores = promiseHooks.onBefore(before); |
| 1052 | +const stopWatchingAfters = promiseHooks.onAfter(after); |
| 1053 | + |
| 1054 | +// Or they may be started and stopped in groups |
| 1055 | +const stopHookSet = promiseHooks.createHook({ |
| 1056 | + init, |
| 1057 | + settled, |
| 1058 | + before, |
| 1059 | + after, |
| 1060 | +}); |
| 1061 | + |
| 1062 | +// Trigger the hooks by using promises |
| 1063 | +const promisePrint = (word) => Promise.resolve(word).then(console.log); |
| 1064 | +promisePrint('Hello'); |
| 1065 | +promisePrint('World'); |
| 1066 | + |
906 | 1067 | // To stop a hook, call the function returned at its creation. |
907 | 1068 | stopWatchingInits(); |
908 | 1069 | stopWatchingSettleds(); |
@@ -1396,7 +1557,16 @@ is as follows. |
1396 | 1557 |
|
1397 | 1558 | Here's an example. |
1398 | 1559 |
|
1399 | | -```js |
| 1560 | +```mjs |
| 1561 | +import { GCProfiler } from 'node:v8'; |
| 1562 | +const profiler = new GCProfiler(); |
| 1563 | +profiler.start(); |
| 1564 | +setTimeout(() => { |
| 1565 | + console.log(profiler.stop()); |
| 1566 | +}, 1000); |
| 1567 | +``` |
| 1568 | +
|
| 1569 | +```cjs |
1400 | 1570 | const { GCProfiler } = require('node:v8'); |
1401 | 1571 | const profiler = new GCProfiler(); |
1402 | 1572 | profiler.start(); |
@@ -1501,8 +1671,37 @@ otherwise, it returns false. |
1501 | 1671 | If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`. |
1502 | 1672 | Sometimes a `Latin-1` string may also be represented as `UTF16`. |
1503 | 1673 |
|
1504 | | -```js |
| 1674 | +```mjs |
| 1675 | +import { isStringOneByteRepresentation } from 'node:v8'; |
| 1676 | +import { Buffer } from 'node:buffer'; |
| 1677 | + |
| 1678 | +const Encoding = { |
| 1679 | + latin1: 1, |
| 1680 | + utf16le: 2, |
| 1681 | +}; |
| 1682 | +const buffer = Buffer.alloc(100); |
| 1683 | +function writeString(input) { |
| 1684 | + if (isStringOneByteRepresentation(input)) { |
| 1685 | + console.log(`input: '${input}'`); |
| 1686 | + buffer.writeUint8(Encoding.latin1); |
| 1687 | + buffer.writeUint32LE(input.length, 1); |
| 1688 | + buffer.write(input, 5, 'latin1'); |
| 1689 | + console.log(`decoded: '${buffer.toString('latin1', 5, 5 + input.length)}'\n`); |
| 1690 | + } else { |
| 1691 | + console.log(`input: '${input}'`); |
| 1692 | + buffer.writeUint8(Encoding.utf16le); |
| 1693 | + buffer.writeUint32LE(input.length * 2, 1); |
| 1694 | + buffer.write(input, 5, 'utf16le'); |
| 1695 | + console.log(`decoded: '${buffer.toString('utf16le', 5, 5 + input.length * 2)}'`); |
| 1696 | + } |
| 1697 | +} |
| 1698 | +writeString('hello'); |
| 1699 | +writeString('你好'); |
| 1700 | +``` |
| 1701 | +
|
| 1702 | +```cjs |
1505 | 1703 | const { isStringOneByteRepresentation } = require('node:v8'); |
| 1704 | +const { Buffer } = require('node:buffer'); |
1506 | 1705 |
|
1507 | 1706 | const Encoding = { |
1508 | 1707 | latin1: 1, |
@@ -1511,13 +1710,17 @@ const Encoding = { |
1511 | 1710 | const buffer = Buffer.alloc(100); |
1512 | 1711 | function writeString(input) { |
1513 | 1712 | if (isStringOneByteRepresentation(input)) { |
| 1713 | + console.log(`input: '${input}'`); |
1514 | 1714 | buffer.writeUint8(Encoding.latin1); |
1515 | 1715 | buffer.writeUint32LE(input.length, 1); |
1516 | 1716 | buffer.write(input, 5, 'latin1'); |
| 1717 | + console.log(`decoded: '${buffer.toString('latin1', 5, 5 + input.length)}'\n`); |
1517 | 1718 | } else { |
| 1719 | + console.log(`input: '${input}'`); |
1518 | 1720 | buffer.writeUint8(Encoding.utf16le); |
1519 | 1721 | buffer.writeUint32LE(input.length * 2, 1); |
1520 | 1722 | buffer.write(input, 5, 'utf16le'); |
| 1723 | + console.log(`decoded: '${buffer.toString('utf16le', 5, 5 + input.length * 2)}'`); |
1521 | 1724 | } |
1522 | 1725 | } |
1523 | 1726 | writeString('hello'); |
|