• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# V8
2
3<!--introduced_in=v4.0.0-->
4
5<!-- source_link=lib/v8.js -->
6
7The `v8` module exposes APIs that are specific to the version of [V8][]
8built into the Node.js binary. It can be accessed using:
9
10```js
11const v8 = require('v8');
12```
13
14The APIs and implementation are subject to change at any time.
15
16## `v8.cachedDataVersionTag()`
17<!-- YAML
18added: v8.0.0
19-->
20
21* Returns: {integer}
22
23Returns an integer representing a "version tag" derived from the V8 version,
24command line flags and detected CPU features. This is useful for determining
25whether a [`vm.Script`][] `cachedData` buffer is compatible with this instance
26of V8.
27
28## `v8.getHeapSpaceStatistics()`
29<!-- YAML
30added: v6.0.0
31changes:
32  - version: v7.5.0
33    pr-url: https://github.com/nodejs/node/pull/10186
34    description: Support values exceeding the 32-bit unsigned integer range.
35-->
36
37* Returns: {Object[]}
38
39Returns statistics about the V8 heap spaces, i.e. the segments which make up
40the V8 heap. Neither the ordering of heap spaces, nor the availability of a
41heap space can be guaranteed as the statistics are provided via the V8
42[`GetHeapSpaceStatistics`][] function and may change from one V8 version to the
43next.
44
45The value returned is an array of objects containing the following properties:
46
47* `space_name` {string}
48* `space_size` {number}
49* `space_used_size` {number}
50* `space_available_size` {number}
51* `physical_space_size` {number}
52
53```json
54[
55  {
56    "space_name": "new_space",
57    "space_size": 2063872,
58    "space_used_size": 951112,
59    "space_available_size": 80824,
60    "physical_space_size": 2063872
61  },
62  {
63    "space_name": "old_space",
64    "space_size": 3090560,
65    "space_used_size": 2493792,
66    "space_available_size": 0,
67    "physical_space_size": 3090560
68  },
69  {
70    "space_name": "code_space",
71    "space_size": 1260160,
72    "space_used_size": 644256,
73    "space_available_size": 960,
74    "physical_space_size": 1260160
75  },
76  {
77    "space_name": "map_space",
78    "space_size": 1094160,
79    "space_used_size": 201608,
80    "space_available_size": 0,
81    "physical_space_size": 1094160
82  },
83  {
84    "space_name": "large_object_space",
85    "space_size": 0,
86    "space_used_size": 0,
87    "space_available_size": 1490980608,
88    "physical_space_size": 0
89  }
90]
91```
92
93## `v8.getHeapSnapshot()`
94<!-- YAML
95added: v11.13.0
96-->
97
98* Returns: {stream.Readable} A Readable Stream containing the V8 heap snapshot
99
100Generates a snapshot of the current V8 heap and returns a Readable
101Stream that may be used to read the JSON serialized representation.
102This JSON stream format is intended to be used with tools such as
103Chrome DevTools. The JSON schema is undocumented and specific to the
104V8 engine, and may change from one version of V8 to the next.
105
106```js
107const stream = v8.getHeapSnapshot();
108stream.pipe(process.stdout);
109```
110
111## `v8.getHeapStatistics()`
112<!-- YAML
113added: v1.0.0
114changes:
115  - version: v7.2.0
116    pr-url: https://github.com/nodejs/node/pull/8610
117    description: Added `malloced_memory`, `peak_malloced_memory`,
118                 and `does_zap_garbage`.
119  - version: v7.5.0
120    pr-url: https://github.com/nodejs/node/pull/10186
121    description: Support values exceeding the 32-bit unsigned integer range.
122-->
123
124* Returns: {Object}
125
126Returns an object with the following properties:
127
128* `total_heap_size` {number}
129* `total_heap_size_executable` {number}
130* `total_physical_size` {number}
131* `total_available_size` {number}
132* `used_heap_size` {number}
133* `heap_size_limit` {number}
134* `malloced_memory` {number}
135* `peak_malloced_memory` {number}
136* `does_zap_garbage` {number}
137* `number_of_native_contexts` {number}
138* `number_of_detached_contexts` {number}
139
140`does_zap_garbage` is a 0/1 boolean, which signifies whether the
141`--zap_code_space` option is enabled or not. This makes V8 overwrite heap
142garbage with a bit pattern. The RSS footprint (resident memory set) gets bigger
143because it continuously touches all heap pages and that makes them less likely
144to get swapped out by the operating system.
145
146`number_of_native_contexts` The value of native_context is the number of the
147top-level contexts currently active. Increase of this number over time indicates
148a memory leak.
149
150`number_of_detached_contexts` The value of detached_context is the number
151of contexts that were detached and not yet garbage collected. This number
152being non-zero indicates a potential memory leak.
153
154<!-- eslint-skip -->
155```js
156{
157  total_heap_size: 7326976,
158  total_heap_size_executable: 4194304,
159  total_physical_size: 7326976,
160  total_available_size: 1152656,
161  used_heap_size: 3476208,
162  heap_size_limit: 1535115264,
163  malloced_memory: 16384,
164  peak_malloced_memory: 1127496,
165  does_zap_garbage: 0,
166  number_of_native_contexts: 1,
167  number_of_detached_contexts: 0
168}
169```
170
171## `v8.getHeapCodeStatistics()`
172<!-- YAML
173added: v12.8.0
174-->
175
176* Returns: {Object}
177
178Returns an object with the following properties:
179
180* `code_and_metadata_size` {number}
181* `bytecode_and_metadata_size` {number}
182* `external_script_source_size` {number}
183
184<!-- eslint-skip -->
185```js
186{
187  code_and_metadata_size: 212208,
188  bytecode_and_metadata_size: 161368,
189  external_script_source_size: 1410794
190}
191```
192
193## `v8.setFlagsFromString(flags)`
194<!-- YAML
195added: v1.0.0
196-->
197
198* `flags` {string}
199
200The `v8.setFlagsFromString()` method can be used to programmatically set
201V8 command line flags. This method should be used with care. Changing settings
202after the VM has started may result in unpredictable behavior, including
203crashes and data loss; or it may simply do nothing.
204
205The V8 options available for a version of Node.js may be determined by running
206`node --v8-options`.
207
208Usage:
209
210```js
211// Print GC events to stdout for one minute.
212const v8 = require('v8');
213v8.setFlagsFromString('--trace_gc');
214setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
215```
216
217## `v8.writeHeapSnapshot([filename])`
218<!-- YAML
219added: v11.13.0
220-->
221
222* `filename` {string} The file path where the V8 heap snapshot is to be
223  saved. If not specified, a file name with the pattern
224  `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be
225  generated, where `{pid}` will be the PID of the Node.js process,
226  `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from
227  the main Node.js thread or the id of a worker thread.
228* Returns: {string} The filename where the snapshot was saved.
229
230Generates a snapshot of the current V8 heap and writes it to a JSON
231file. This file is intended to be used with tools such as Chrome
232DevTools. The JSON schema is undocumented and specific to the V8
233engine, and may change from one version of V8 to the next.
234
235A heap snapshot is specific to a single V8 isolate. When using
236[worker threads][], a heap snapshot generated from the main thread will
237not contain any information about the workers, and vice versa.
238
239```js
240const { writeHeapSnapshot } = require('v8');
241const {
242  Worker,
243  isMainThread,
244  parentPort
245} = require('worker_threads');
246
247if (isMainThread) {
248  const worker = new Worker(__filename);
249
250  worker.once('message', (filename) => {
251    console.log(`worker heapdump: ${filename}`);
252    // Now get a heapdump for the main thread.
253    console.log(`main thread heapdump: ${writeHeapSnapshot()}`);
254  });
255
256  // Tell the worker to create a heapdump.
257  worker.postMessage('heapdump');
258} else {
259  parentPort.once('message', (message) => {
260    if (message === 'heapdump') {
261      // Generate a heapdump for the worker
262      // and return the filename to the parent.
263      parentPort.postMessage(writeHeapSnapshot());
264    }
265  });
266}
267```
268
269## Serialization API
270
271The serialization API provides means of serializing JavaScript values in a way
272that is compatible with the [HTML structured clone algorithm][].
273
274The format is backward-compatible (i.e. safe to store to disk).
275Equal JavaScript values may result in different serialized output.
276
277### `v8.serialize(value)`
278<!-- YAML
279added: v8.0.0
280-->
281
282* `value` {any}
283* Returns: {Buffer}
284
285Uses a [`DefaultSerializer`][] to serialize `value` into a buffer.
286
287### `v8.deserialize(buffer)`
288<!-- YAML
289added: v8.0.0
290-->
291
292* `buffer` {Buffer|TypedArray|DataView} A buffer returned by [`serialize()`][].
293
294Uses a [`DefaultDeserializer`][] with default options to read a JS value
295from a buffer.
296
297### Class: `v8.Serializer`
298<!-- YAML
299added: v8.0.0
300-->
301
302#### `new Serializer()`
303Creates a new `Serializer` object.
304
305#### `serializer.writeHeader()`
306
307Writes out a header, which includes the serialization format version.
308
309#### `serializer.writeValue(value)`
310
311* `value` {any}
312
313Serializes a JavaScript value and adds the serialized representation to the
314internal buffer.
315
316This throws an error if `value` cannot be serialized.
317
318#### `serializer.releaseBuffer()`
319
320* Returns: {Buffer}
321
322Returns the stored internal buffer. This serializer should not be used once
323the buffer is released. Calling this method results in undefined behavior
324if a previous write has failed.
325
326#### `serializer.transferArrayBuffer(id, arrayBuffer)`
327
328* `id` {integer} A 32-bit unsigned integer.
329* `arrayBuffer` {ArrayBuffer} An `ArrayBuffer` instance.
330
331Marks an `ArrayBuffer` as having its contents transferred out of band.
332Pass the corresponding `ArrayBuffer` in the deserializing context to
333[`deserializer.transferArrayBuffer()`][].
334
335#### `serializer.writeUint32(value)`
336
337* `value` {integer}
338
339Write a raw 32-bit unsigned integer.
340For use inside of a custom [`serializer._writeHostObject()`][].
341
342#### `serializer.writeUint64(hi, lo)`
343
344* `hi` {integer}
345* `lo` {integer}
346
347Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.
348For use inside of a custom [`serializer._writeHostObject()`][].
349
350#### `serializer.writeDouble(value)`
351
352* `value` {number}
353
354Write a JS `number` value.
355For use inside of a custom [`serializer._writeHostObject()`][].
356
357#### `serializer.writeRawBytes(buffer)`
358
359* `buffer` {Buffer|TypedArray|DataView}
360
361Write raw bytes into the serializer’s internal buffer. The deserializer
362will require a way to compute the length of the buffer.
363For use inside of a custom [`serializer._writeHostObject()`][].
364
365#### `serializer._writeHostObject(object)`
366
367* `object` {Object}
368
369This method is called to write some kind of host object, i.e. an object created
370by native C++ bindings. If it is not possible to serialize `object`, a suitable
371exception should be thrown.
372
373This method is not present on the `Serializer` class itself but can be provided
374by subclasses.
375
376#### `serializer._getDataCloneError(message)`
377
378* `message` {string}
379
380This method is called to generate error objects that will be thrown when an
381object can not be cloned.
382
383This method defaults to the [`Error`][] constructor and can be overridden on
384subclasses.
385
386#### `serializer._getSharedArrayBufferId(sharedArrayBuffer)`
387
388* `sharedArrayBuffer` {SharedArrayBuffer}
389
390This method is called when the serializer is going to serialize a
391`SharedArrayBuffer` object. It must return an unsigned 32-bit integer ID for
392the object, using the same ID if this `SharedArrayBuffer` has already been
393serialized. When deserializing, this ID will be passed to
394[`deserializer.transferArrayBuffer()`][].
395
396If the object cannot be serialized, an exception should be thrown.
397
398This method is not present on the `Serializer` class itself but can be provided
399by subclasses.
400
401#### `serializer._setTreatArrayBufferViewsAsHostObjects(flag)`
402
403* `flag` {boolean} **Default:** `false`
404
405Indicate whether to treat `TypedArray` and `DataView` objects as
406host objects, i.e. pass them to [`serializer._writeHostObject()`][].
407
408### Class: `v8.Deserializer`
409<!-- YAML
410added: v8.0.0
411-->
412
413#### `new Deserializer(buffer)`
414
415* `buffer` {Buffer|TypedArray|DataView} A buffer returned by
416  [`serializer.releaseBuffer()`][].
417
418Creates a new `Deserializer` object.
419
420#### `deserializer.readHeader()`
421
422Reads and validates a header (including the format version).
423May, for example, reject an invalid or unsupported wire format. In that case,
424an `Error` is thrown.
425
426#### `deserializer.readValue()`
427
428Deserializes a JavaScript value from the buffer and returns it.
429
430#### `deserializer.transferArrayBuffer(id, arrayBuffer)`
431
432* `id` {integer} A 32-bit unsigned integer.
433* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An `ArrayBuffer` instance.
434
435Marks an `ArrayBuffer` as having its contents transferred out of band.
436Pass the corresponding `ArrayBuffer` in the serializing context to
437[`serializer.transferArrayBuffer()`][] (or return the `id` from
438[`serializer._getSharedArrayBufferId()`][] in the case of `SharedArrayBuffer`s).
439
440#### `deserializer.getWireFormatVersion()`
441
442* Returns: {integer}
443
444Reads the underlying wire format version. Likely mostly to be useful to
445legacy code reading old wire format versions. May not be called before
446`.readHeader()`.
447
448#### `deserializer.readUint32()`
449
450* Returns: {integer}
451
452Read a raw 32-bit unsigned integer and return it.
453For use inside of a custom [`deserializer._readHostObject()`][].
454
455#### `deserializer.readUint64()`
456
457* Returns: {integer[]}
458
459Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]`
460with two 32-bit unsigned integer entries.
461For use inside of a custom [`deserializer._readHostObject()`][].
462
463#### `deserializer.readDouble()`
464
465* Returns: {number}
466
467Read a JS `number` value.
468For use inside of a custom [`deserializer._readHostObject()`][].
469
470#### `deserializer.readRawBytes(length)`
471
472* `length` {integer}
473* Returns: {Buffer}
474
475Read raw bytes from the deserializer’s internal buffer. The `length` parameter
476must correspond to the length of the buffer that was passed to
477[`serializer.writeRawBytes()`][].
478For use inside of a custom [`deserializer._readHostObject()`][].
479
480#### `deserializer._readHostObject()`
481
482This method is called to read some kind of host object, i.e. an object that is
483created by native C++ bindings. If it is not possible to deserialize the data,
484a suitable exception should be thrown.
485
486This method is not present on the `Deserializer` class itself but can be
487provided by subclasses.
488
489### Class: `v8.DefaultSerializer`
490<!-- YAML
491added: v8.0.0
492-->
493
494A subclass of [`Serializer`][] that serializes `TypedArray`
495(in particular [`Buffer`][]) and `DataView` objects as host objects, and only
496stores the part of their underlying `ArrayBuffer`s that they are referring to.
497
498### Class: `v8.DefaultDeserializer`
499<!-- YAML
500added: v8.0.0
501-->
502
503A subclass of [`Deserializer`][] corresponding to the format written by
504[`DefaultSerializer`][].
505
506[`Buffer`]: buffer.html
507[`DefaultDeserializer`]: #v8_class_v8_defaultdeserializer
508[`DefaultSerializer`]: #v8_class_v8_defaultserializer
509[`Deserializer`]: #v8_class_v8_deserializer
510[`Error`]: errors.html#errors_class_error
511[`GetHeapSpaceStatistics`]: https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4
512[`Serializer`]: #v8_class_v8_serializer
513[`deserializer._readHostObject()`]: #v8_deserializer_readhostobject
514[`deserializer.transferArrayBuffer()`]: #v8_deserializer_transferarraybuffer_id_arraybuffer
515[`serialize()`]: #v8_v8_serialize_value
516[`serializer._getSharedArrayBufferId()`]: #v8_serializer_getsharedarraybufferid_sharedarraybuffer
517[`serializer._writeHostObject()`]: #v8_serializer_writehostobject_object
518[`serializer.releaseBuffer()`]: #v8_serializer_releasebuffer
519[`serializer.transferArrayBuffer()`]: #v8_serializer_transferarraybuffer_id_arraybuffer
520[`serializer.writeRawBytes()`]: #v8_serializer_writerawbytes_buffer
521[`vm.Script`]: vm.html#vm_new_vm_script_code_options
522[HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
523[V8]: https://developers.google.com/v8/
524[worker threads]: worker_threads.html
525