Source Code: lib/v8.js
The node:v8 module exposes APIs that are specific to the version of V8\nbuilt into the Node.js binary. It can be accessed using:
node:v8
const v8 = require('node:v8');\n
Returns an integer representing a version tag derived from the V8 version,\ncommand-line flags, and detected CPU features. This is useful for determining\nwhether a vm.Script cachedData buffer is compatible with this instance\nof V8.
vm.Script
cachedData
console.log(v8.cachedDataVersionTag()); // 3947234607\n// The value returned by v8.cachedDataVersionTag() is derived from the V8\n// version, command-line flags, and detected CPU features. Test that the value\n// does indeed update when flags are toggled.\nv8.setFlagsFromString('--allow_natives_syntax');\nconsole.log(v8.cachedDataVersionTag()); // 183726201\n
Returns an object with the following properties:
code_and_metadata_size
bytecode_and_metadata_size
external_script_source_size
{\n code_and_metadata_size: 212208,\n bytecode_and_metadata_size: 161368,\n external_script_source_size: 1410794\n}\n
Generates a snapshot of the current V8 heap and returns a Readable\nStream that may be used to read the JSON serialized representation.\nThis JSON stream format is intended to be used with tools such as\nChrome DevTools. The JSON schema is undocumented and specific to the\nV8 engine. Therefore, the schema may change from one version of V8 to the next.
Creating a heap snapshot requires memory about twice the size of the heap at\nthe time the snapshot is created. This results in the risk of OOM killers\nterminating the process.
Generating a snapshot is a synchronous operation which blocks the event loop\nfor a duration depending on the heap size.
// Print heap snapshot to the console\nconst v8 = require('node:v8');\nconst stream = v8.getHeapSnapshot();\nstream.pipe(process.stdout);\n
Returns statistics about the V8 heap spaces, i.e. the segments which make up\nthe V8 heap. Neither the ordering of heap spaces, nor the availability of a\nheap space can be guaranteed as the statistics are provided via the V8\nGetHeapSpaceStatistics function and may change from one V8 version to the\nnext.
GetHeapSpaceStatistics
The value returned is an array of objects containing the following properties:
space_name
space_size
space_used_size
space_available_size
physical_space_size
[\n {\n \"space_name\": \"new_space\",\n \"space_size\": 2063872,\n \"space_used_size\": 951112,\n \"space_available_size\": 80824,\n \"physical_space_size\": 2063872\n },\n {\n \"space_name\": \"old_space\",\n \"space_size\": 3090560,\n \"space_used_size\": 2493792,\n \"space_available_size\": 0,\n \"physical_space_size\": 3090560\n },\n {\n \"space_name\": \"code_space\",\n \"space_size\": 1260160,\n \"space_used_size\": 644256,\n \"space_available_size\": 960,\n \"physical_space_size\": 1260160\n },\n {\n \"space_name\": \"map_space\",\n \"space_size\": 1094160,\n \"space_used_size\": 201608,\n \"space_available_size\": 0,\n \"physical_space_size\": 1094160\n },\n {\n \"space_name\": \"large_object_space\",\n \"space_size\": 0,\n \"space_used_size\": 0,\n \"space_available_size\": 1490980608,\n \"physical_space_size\": 0\n }\n]\n
total_heap_size
total_heap_size_executable
total_physical_size
total_available_size
used_heap_size
heap_size_limit
malloced_memory
peak_malloced_memory
does_zap_garbage
number_of_native_contexts
number_of_detached_contexts
total_global_handles_size
used_global_handles_size
external_memory
does_zap_garbage is a 0/1 boolean, which signifies whether the\n--zap_code_space option is enabled or not. This makes V8 overwrite heap\ngarbage with a bit pattern. The RSS footprint (resident set size) gets bigger\nbecause it continuously touches all heap pages and that makes them less likely\nto get swapped out by the operating system.
--zap_code_space
number_of_native_contexts The value of native_context is the number of the\ntop-level contexts currently active. Increase of this number over time indicates\na memory leak.
number_of_detached_contexts The value of detached_context is the number\nof contexts that were detached and not yet garbage collected. This number\nbeing non-zero indicates a potential memory leak.
total_global_handles_size The value of total_global_handles_size is the\ntotal memory size of V8 global handles.
used_global_handles_size The value of used_global_handles_size is the\nused memory size of V8 global handles.
external_memory The value of external_memory is the memory size of array\nbuffers and external strings.
{\n total_heap_size: 7326976,\n total_heap_size_executable: 4194304,\n total_physical_size: 7326976,\n total_available_size: 1152656,\n used_heap_size: 3476208,\n heap_size_limit: 1535115264,\n malloced_memory: 16384,\n peak_malloced_memory: 1127496,\n does_zap_garbage: 0,\n number_of_native_contexts: 1,\n number_of_detached_contexts: 0,\n total_global_handles_size: 8192,\n used_global_handles_size: 3296,\n external_memory: 318824\n}\n
The v8.setFlagsFromString() method can be used to programmatically set\nV8 command-line flags. This method should be used with care. Changing settings\nafter the VM has started may result in unpredictable behavior, including\ncrashes and data loss; or it may simply do nothing.
v8.setFlagsFromString()
The V8 options available for a version of Node.js may be determined by running\nnode --v8-options.
node --v8-options
Usage:
// Print GC events to stdout for one minute.\nconst v8 = require('node:v8');\nv8.setFlagsFromString('--trace_gc');\nsetTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);\n
The v8.stopCoverage() method allows the user to stop the coverage collection\nstarted by NODE_V8_COVERAGE, so that V8 can release the execution count\nrecords and optimize code. This can be used in conjunction with\nv8.takeCoverage() if the user wants to collect the coverage on demand.
v8.stopCoverage()
NODE_V8_COVERAGE
v8.takeCoverage()
The v8.takeCoverage() method allows the user to write the coverage started by\nNODE_V8_COVERAGE to disk on demand. This method can be invoked multiple\ntimes during the lifetime of the process. Each time the execution counter will\nbe reset and a new coverage report will be written to the directory specified\nby NODE_V8_COVERAGE.
When the process is about to exit, one last coverage will still be written to\ndisk unless v8.stopCoverage() is invoked before the process exits.
Generates a snapshot of the current V8 heap and writes it to a JSON\nfile. This file is intended to be used with tools such as Chrome\nDevTools. The JSON schema is undocumented and specific to the V8\nengine, and may change from one version of V8 to the next.
A heap snapshot is specific to a single V8 isolate. When using\nworker threads, a heap snapshot generated from the main thread will\nnot contain any information about the workers, and vice versa.
const { writeHeapSnapshot } = require('node:v8');\nconst {\n Worker,\n isMainThread,\n parentPort\n} = require('node:worker_threads');\n\nif (isMainThread) {\n const worker = new Worker(__filename);\n\n worker.once('message', (filename) => {\n console.log(`worker heapdump: ${filename}`);\n // Now get a heapdump for the main thread.\n console.log(`main thread heapdump: ${writeHeapSnapshot()}`);\n });\n\n // Tell the worker to create a heapdump.\n worker.postMessage('heapdump');\n} else {\n parentPort.once('message', (message) => {\n if (message === 'heapdump') {\n // Generate a heapdump for the worker\n // and return the filename to the parent.\n parentPort.postMessage(writeHeapSnapshot());\n }\n });\n}\n
The API is a no-op if --heapsnapshot-near-heap-limit is already set from the\ncommand line or the API is called more than once. limit must be a positive\ninteger. See --heapsnapshot-near-heap-limit for more information.
--heapsnapshot-near-heap-limit
limit
The serialization API provides means of serializing JavaScript values in a way\nthat is compatible with the HTML structured clone algorithm.
The format is backward-compatible (i.e. safe to store to disk).\nEqual JavaScript values may result in different serialized output.
Uses a DefaultSerializer to serialize value into a buffer.
DefaultSerializer
value
ERR_BUFFER_TOO_LARGE will be thrown when trying to\nserialize a huge object which requires buffer\nlarger than buffer.constants.MAX_LENGTH.
ERR_BUFFER_TOO_LARGE
buffer.constants.MAX_LENGTH
Uses a DefaultDeserializer with default options to read a JS value\nfrom a buffer.
DefaultDeserializer
Writes out a header, which includes the serialization format version.
Serializes a JavaScript value and adds the serialized representation to the\ninternal buffer.
This throws an error if value cannot be serialized.
Returns the stored internal buffer. This serializer should not be used once\nthe buffer is released. Calling this method results in undefined behavior\nif a previous write has failed.
Marks an ArrayBuffer as having its contents transferred out of band.\nPass the corresponding ArrayBuffer in the deserializing context to\ndeserializer.transferArrayBuffer().
ArrayBuffer
deserializer.transferArrayBuffer()
Write a raw 32-bit unsigned integer.\nFor use inside of a custom serializer._writeHostObject().
serializer._writeHostObject()
Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.\nFor use inside of a custom serializer._writeHostObject().
Write a JS number value.\nFor use inside of a custom serializer._writeHostObject().
number
Write raw bytes into the serializer's internal buffer. The deserializer\nwill require a way to compute the length of the buffer.\nFor use inside of a custom serializer._writeHostObject().
This method is called to write some kind of host object, i.e. an object created\nby native C++ bindings. If it is not possible to serialize object, a suitable\nexception should be thrown.
object
This method is not present on the Serializer class itself but can be provided\nby subclasses.
Serializer
This method is called to generate error objects that will be thrown when an\nobject can not be cloned.
This method defaults to the Error constructor and can be overridden on\nsubclasses.
Error
This method is called when the serializer is going to serialize a\nSharedArrayBuffer object. It must return an unsigned 32-bit integer ID for\nthe object, using the same ID if this SharedArrayBuffer has already been\nserialized. When deserializing, this ID will be passed to\ndeserializer.transferArrayBuffer().
SharedArrayBuffer
If the object cannot be serialized, an exception should be thrown.
Indicate whether to treat TypedArray and DataView objects as\nhost objects, i.e. pass them to serializer._writeHostObject().
TypedArray
DataView
Creates a new Serializer object.
Reads and validates a header (including the format version).\nMay, for example, reject an invalid or unsupported wire format. In that case,\nan Error is thrown.
Deserializes a JavaScript value from the buffer and returns it.
Marks an ArrayBuffer as having its contents transferred out of band.\nPass the corresponding ArrayBuffer in the serializing context to\nserializer.transferArrayBuffer() (or return the id from\nserializer._getSharedArrayBufferId() in the case of SharedArrayBuffers).
serializer.transferArrayBuffer()
id
serializer._getSharedArrayBufferId()
Reads the underlying wire format version. Likely mostly to be useful to\nlegacy code reading old wire format versions. May not be called before\n.readHeader().
.readHeader()
Read a raw 32-bit unsigned integer and return it.\nFor use inside of a custom deserializer._readHostObject().
deserializer._readHostObject()
Read a raw 64-bit unsigned integer and return it as an array [hi, lo]\nwith two 32-bit unsigned integer entries.\nFor use inside of a custom deserializer._readHostObject().
[hi, lo]
Read a JS number value.\nFor use inside of a custom deserializer._readHostObject().
Read raw bytes from the deserializer's internal buffer. The length parameter\nmust correspond to the length of the buffer that was passed to\nserializer.writeRawBytes().\nFor use inside of a custom deserializer._readHostObject().
length
serializer.writeRawBytes()
This method is called to read some kind of host object, i.e. an object that is\ncreated by native C++ bindings. If it is not possible to deserialize the data,\na suitable exception should be thrown.
This method is not present on the Deserializer class itself but can be\nprovided by subclasses.
Deserializer
Creates a new Deserializer object.
A subclass of Serializer that serializes TypedArray\n(in particular Buffer) and DataView objects as host objects, and only\nstores the part of their underlying ArrayBuffers that they are referring to.
Buffer
A subclass of Deserializer corresponding to the format written by\nDefaultSerializer.
The promiseHooks interface can be used to track promise lifecycle events.\nTo track all async activity, see async_hooks which internally uses this\nmodule to produce promise lifecycle events in addition to events for other\nasync resources. For request context management, see AsyncLocalStorage.
promiseHooks
async_hooks
AsyncLocalStorage
import { promiseHooks } from 'node:v8';\n\n// There are four lifecycle events produced by promises:\n\n// The `init` event represents the creation of a promise. This could be a\n// direct creation such as with `new Promise(...)` or a continuation such\n// as `then()` or `catch()`. It also happens whenever an async function is\n// called or does an `await`. If a continuation promise is created, the\n// `parent` will be the promise it is a continuation from.\nfunction init(promise, parent) {\n console.log('a promise was created', { promise, parent });\n}\n\n// The `settled` event happens when a promise receives a resolution or\n// rejection value. This may happen synchronously such as when using\n// `Promise.resolve()` on non-promise input.\nfunction settled(promise) {\n console.log('a promise resolved or rejected', { promise });\n}\n\n// The `before` event runs immediately before a `then()` or `catch()` handler\n// runs or an `await` resumes execution.\nfunction before(promise) {\n console.log('a promise is about to call a then handler', { promise });\n}\n\n// The `after` event runs immediately after a `then()` handler runs or when\n// an `await` begins after resuming from another.\nfunction after(promise) {\n console.log('a promise is done calling a then handler', { promise });\n}\n\n// Lifecycle hooks may be started and stopped individually\nconst stopWatchingInits = promiseHooks.onInit(init);\nconst stopWatchingSettleds = promiseHooks.onSettled(settled);\nconst stopWatchingBefores = promiseHooks.onBefore(before);\nconst stopWatchingAfters = promiseHooks.onAfter(after);\n\n// Or they may be started and stopped in groups\nconst stopHookSet = promiseHooks.createHook({\n init,\n settled,\n before,\n after\n});\n\n// To stop a hook, call the function returned at its creation.\nstopWatchingInits();\nstopWatchingSettleds();\nstopWatchingBefores();\nstopWatchingAfters();\nstopHookSet();\n
The init hook must be a plain function. Providing an async function will\nthrow as it would produce an infinite microtask loop.
init
import { promiseHooks } from 'node:v8';\n\nconst stop = promiseHooks.onInit((promise, parent) => {});\n
const { promiseHooks } = require('node:v8');\n\nconst stop = promiseHooks.onInit((promise, parent) => {});\n
The settled hook must be a plain function. Providing an async function will\nthrow as it would produce an infinite microtask loop.
settled
import { promiseHooks } from 'node:v8';\n\nconst stop = promiseHooks.onSettled((promise) => {});\n
const { promiseHooks } = require('node:v8');\n\nconst stop = promiseHooks.onSettled((promise) => {});\n
The before hook must be a plain function. Providing an async function will\nthrow as it would produce an infinite microtask loop.
before
import { promiseHooks } from 'node:v8';\n\nconst stop = promiseHooks.onBefore((promise) => {});\n
const { promiseHooks } = require('node:v8');\n\nconst stop = promiseHooks.onBefore((promise) => {});\n
The after hook must be a plain function. Providing an async function will\nthrow as it would produce an infinite microtask loop.
after
import { promiseHooks } from 'node:v8';\n\nconst stop = promiseHooks.onAfter((promise) => {});\n
const { promiseHooks } = require('node:v8');\n\nconst stop = promiseHooks.onAfter((promise) => {});\n
The hook callbacks must be plain functions. Providing async functions will\nthrow as it would produce an infinite microtask loop.
Registers functions to be called for different lifetime events of each promise.
The callbacks init()/before()/after()/settled() are called for the\nrespective events during a promise's lifetime.
init()
before()
after()
settled()
All callbacks are optional. For example, if only promise creation needs to\nbe tracked, then only the init callback needs to be passed. The\nspecifics of all functions that can be passed to callbacks is in the\nHook Callbacks section.
callbacks
import { promiseHooks } from 'node:v8';\n\nconst stopAll = promiseHooks.createHook({\n init(promise, parent) {}\n});\n
const { promiseHooks } = require('node:v8');\n\nconst stopAll = promiseHooks.createHook({\n init(promise, parent) {}\n});\n
Key events in the lifetime of a promise have been categorized into four areas:\ncreation of a promise, before/after a continuation handler is called or around\nan await, and when the promise resolves or rejects.
While these hooks are similar to those of async_hooks they lack a\ndestroy hook. Other types of async resources typically represent sockets or\nfile descriptors which have a distinct \"closed\" state to express the destroy\nlifecycle event while promises remain usable for as long as code can still\nreach them. Garbage collection tracking is used to make promises fit into the\nasync_hooks event model, however this tracking is very expensive and they may\nnot necessarily ever even be garbage collected.
destroy
Because promises are asynchronous resources whose lifecycle is tracked\nvia the promise hooks mechanism, the init(), before(), after(), and\nsettled() callbacks must not be async functions as they create more\npromises which would produce an infinite loop.
While this API is used to feed promise events into async_hooks, the\nordering between the two is undefined. Both APIs are multi-tenant\nand therefore could produce events in any order relative to each other.
Called when a promise is constructed. This does not mean that corresponding\nbefore/after events will occur, only that the possibility exists. This will\nhappen if a promise is created without ever getting a continuation.
Called before a promise continuation executes. This can be in the form of\nthen(), catch(), or finally() handlers or an await resuming.
then()
catch()
finally()
await
The before callback will be called 0 to N times. The before callback\nwill typically be called 0 times if no continuation was ever made for the\npromise. The before callback may be called many times in the case where\nmany continuations have been made from the same promise.
Called immediately after a promise continuation executes. This may be after a\nthen(), catch(), or finally() handler or before an await after another\nawait.
Called when the promise receives a resolution or rejection value. This may\noccur synchronously in the case of Promise.resolve() or Promise.reject().
Promise.resolve()
Promise.reject()
The v8.startupSnapshot interface can be used to add serialization and\ndeserialization hooks for custom startup snapshots. Currently the startup\nsnapshots can only be built into the Node.js binary from source.
v8.startupSnapshot
$ cd /path/to/node\n$ ./configure --node-snapshot-main=entry.js\n$ make node\n# This binary contains the result of the execution of entry.js\n$ out/Release/node\n
In the example above, entry.js can use methods from the v8.startupSnapshot\ninterface to specify how to save information for custom objects in the snapshot\nduring serialization and how the information can be used to synchronize these\nobjects during deserialization of the snapshot. For example, if the entry.js\ncontains the following script:
entry.js
'use strict';\n\nconst fs = require('fs');\nconst zlib = require('zlib');\nconst path = require('path');\nconst assert = require('assert');\n\nconst {\n isBuildingSnapshot,\n addSerializeCallback,\n addDeserializeCallback,\n setDeserializeMainFunction\n} = require('v8').startupSnapshot;\n\nconst filePath = path.resolve(__dirname, '../x1024.txt');\nconst storage = {};\n\nassert(isBuildingSnapshot());\n\naddSerializeCallback(({ filePath }) => {\n storage[filePath] = zlib.gzipSync(fs.readFileSync(filePath));\n}, { filePath });\n\naddDeserializeCallback(({ filePath }) => {\n storage[filePath] = zlib.gunzipSync(storage[filePath]);\n}, { filePath });\n\nsetDeserializeMainFunction(({ filePath }) => {\n console.log(storage[filePath].toString());\n}, { filePath });\n
The resulted binary will simply print the data deserialized from the snapshot\nduring start up:
$ out/Release/node\n# Prints content of ./test/fixtures/x1024.txt\n
Currently the API is only available to a Node.js instance launched from the\ndefault snapshot, that is, the application deserialized from a user-land\nsnapshot cannot use these APIs again.
Add a callback that will be called when the Node.js instance is about to\nget serialized into a snapshot and exit. This can be used to release\nresources that should not or cannot be serialized or to convert user data\ninto a form more suitable for serialization.
Add a callback that will be called when the Node.js instance is deserialized\nfrom a snapshot. The callback and the data (if provided) will be\nserialized into the snapshot, they can be used to re-initialize the state\nof the application or to re-acquire resources that the application needs\nwhen the application is restarted from the snapshot.
callback
data
This sets the entry point of the Node.js application when it is deserialized\nfrom a snapshot. This can be called only once in the snapshot building\nscript. If called, the deserialized application no longer needs an additional\nentry point script to start up and will simply invoke the callback along with\nthe deserialized data (if provided), otherwise an entry point script still\nneeds to be provided to the deserialized application.
Returns true if the Node.js instance is run to build a snapshot.