Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 3d23bcd

Browse filesBrowse files
mfdebianaduh95
authored andcommitted
doc: add esm and cjs examples to node:v8
PR-URL: #61328 Reviewed-By: Aviv Keller <me@aviv.sh> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Zeyu "Alex" Yang <himself65@outlook.com> Reviewed-By: Ulises Gascón <ulisesgascongonzalez@gmail.com>
1 parent 1d15955 commit 3d23bcd
Copy full SHA for 3d23bcd

1 file changed

+217-14Lines changed: 217 additions & 14 deletions

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎doc/api/v8.md‎

Copy file name to clipboardExpand all lines: doc/api/v8.md
+217-14Lines changed: 217 additions & 14 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,11 @@
77
The `node:v8` module exposes APIs that are specific to the version of [V8][]
88
built into the Node.js binary. It can be accessed using:
99

10-
```js
10+
```mjs
11+
import v8 from 'node:v8';
12+
```
13+
14+
```cjs
1115
const v8 = require('node:v8');
1216
```
1317

@@ -92,9 +96,18 @@ terminating the process.
9296
Generating a snapshot is a synchronous operation which blocks the event loop
9397
for a duration depending on the heap size.
9498

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+
95107
```js
96108
// Print heap snapshot to the console
97109
const v8 = require('node:v8');
110+
const process = require('node:process');
98111
const stream = v8.getHeapSnapshot();
99112
stream.pipe(process.stdout);
100113
```
@@ -467,11 +480,70 @@ The V8 options available for a version of Node.js may be determined by running
467480

468481
Usage:
469482

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);
475547
```
476548

477549
## `v8.stopCoverage()`
@@ -551,13 +623,37 @@ terminating the process.
551623
Generating a snapshot is a synchronous operation which blocks the event loop
552624
for a duration depending on the heap size.
553625

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
555655
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');
561657

562658
if (isMainThread) {
563659
const worker = new Worker(__filename);
@@ -903,6 +999,71 @@ const stopHookSet = promiseHooks.createHook({
903999
after,
9041000
});
9051001

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+
9061067
// To stop a hook, call the function returned at its creation.
9071068
stopWatchingInits();
9081069
stopWatchingSettleds();
@@ -1396,7 +1557,16 @@ is as follows.
13961557
13971558
Here's an example.
13981559
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
14001570
const { GCProfiler } = require('node:v8');
14011571
const profiler = new GCProfiler();
14021572
profiler.start();
@@ -1501,8 +1671,37 @@ otherwise, it returns false.
15011671
If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`.
15021672
Sometimes a `Latin-1` string may also be represented as `UTF16`.
15031673
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
15051703
const { isStringOneByteRepresentation } = require('node:v8');
1704+
const { Buffer } = require('node:buffer');
15061705

15071706
const Encoding = {
15081707
latin1: 1,
@@ -1511,13 +1710,17 @@ const Encoding = {
15111710
const buffer = Buffer.alloc(100);
15121711
function writeString(input) {
15131712
if (isStringOneByteRepresentation(input)) {
1713+
console.log(`input: '${input}'`);
15141714
buffer.writeUint8(Encoding.latin1);
15151715
buffer.writeUint32LE(input.length, 1);
15161716
buffer.write(input, 5, 'latin1');
1717+
console.log(`decoded: '${buffer.toString('latin1', 5, 5 + input.length)}'\n`);
15171718
} else {
1719+
console.log(`input: '${input}'`);
15181720
buffer.writeUint8(Encoding.utf16le);
15191721
buffer.writeUint32LE(input.length * 2, 1);
15201722
buffer.write(input, 5, 'utf16le');
1723+
console.log(`decoded: '${buffer.toString('utf16le', 5, 5 + input.length * 2)}'`);
15211724
}
15221725
}
15231726
writeString('hello');

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.