Overview
The node:v8 module exposes APIs specific to the version of V8 built into Node.js. V8 is the JavaScript engine that powers Node.js, providing JavaScript execution, compilation, and memory management.
import v8 from 'node:v8' ;
// or
const v8 = require ( 'node:v8' );
V8 is developed by Google and is also used in Chrome browser. Node.js includes a specific version of V8.
V8 Engine Architecture
V8 provides the core JavaScript runtime capabilities:
JavaScript Execution JIT compilation and optimization
Memory Management Garbage collection and heap management
Object Model JavaScript value representation
Key V8 Components
Independent JavaScript execution environment with its own heap v8 ::Isolate * isolate = v8 :: Isolate :: GetCurrent ();
Global execution scope with built-in objects v8 ::Local < v8 ::Context > context = isolate -> GetCurrentContext ();
Memory space where JavaScript objects live const stats = v8 . getHeapStatistics ();
console . log ( stats . used_heap_size );
Heap Statistics
Get Heap Statistics
const stats = v8 . getHeapStatistics ();
console . log ({
totalHeapSize: stats . total_heap_size ,
totalHeapSizeExecutable: stats . total_heap_size_executable ,
totalPhysicalSize: stats . total_physical_size ,
totalAvailableSize: stats . total_available_size ,
usedHeapSize: stats . used_heap_size ,
heapSizeLimit: stats . heap_size_limit ,
mallocedMemory: stats . malloced_memory ,
peakMallocedMemory: stats . peak_malloced_memory ,
numberOfNativeContexts: stats . number_of_native_contexts ,
numberOfDetachedContexts: stats . number_of_detached_contexts
});
Total bytes V8 has allocated for the heap. Grows as used_heap_size increases.
Bytes currently used by V8’s JavaScript objects. Actual memory in active use.
Maximum heap size (default limit or --max-old-space-size value).
Actual physical memory committed, not just reserved.
How much more memory V8 can use before exceeding the limit.
Heap Space Statistics
const spaces = v8 . getHeapSpaceStatistics ();
spaces . forEach ( space => {
console . log ({
name: space . space_name ,
size: space . space_size ,
used: space . space_used_size ,
available: space . space_available_size ,
physical: space . physical_space_size
});
});
Heap Spaces:
new_space - Young generation (short-lived objects)
old_space - Old generation (long-lived objects)
code_space - JIT-compiled code
map_space - Hidden classes and maps
large_object_space - Objects larger than size limits
Heap Snapshots
Capture heap state for memory analysis:
import { getHeapSnapshot } from 'node:v8' ;
import { createWriteStream } from 'node:fs' ;
// Generate and save heap snapshot
const snapshot = getHeapSnapshot ();
const writeStream = createWriteStream ( 'heap.heapsnapshot' );
snapshot . pipe ( writeStream );
Snapshot Options
const snapshot = getHeapSnapshot ({
exposeInternals: true , // Include internal objects
exposeNumericValues: false // Hide numeric values in fields
});
Creating a heap snapshot requires memory about twice the size of the heap and blocks the event loop during generation.
V8 Flags and Options
Setting V8 Flags
import v8 from 'node:v8' ;
// Enable native syntax
v8 . setFlagsFromString ( '--allow_natives_syntax' );
// Check cached data version
console . log ( v8 . cachedDataVersionTag ());
Common V8 Flags
Memory Options
Optimization Flags
Debugging Flags
Experimental Features
node --max-old-space-size=4096 app.js # 4GB heap limit
node --max-new-space-size=1024 app.js # New space size
Heap Code Statistics
const codeStats = v8 . getHeapCodeStatistics ();
console . log ({
codeAndMetadataSize: codeStats . code_and_metadata_size ,
bytecodeAndMetadataSize: codeStats . bytecode_and_metadata_size ,
externalScriptSourceSize: codeStats . external_script_source_size ,
cpuProfilerMetadataSize: codeStats . cpu_profiler_metadata_size
});
Serialization API
Serialize JavaScript Values
import v8 from 'node:v8' ;
// Serialize object
const obj = { name: 'Node.js' , version: 20 };
const serialized = v8 . serialize ( obj );
// Deserialize
const deserialized = v8 . deserialize ( serialized );
console . log ( deserialized ); // { name: 'Node.js', version: 20 }
Custom Serialization
class CustomClass {
constructor ( data ) {
this . data = data ;
}
}
const serializer = new v8 . Serializer ();
serializer . writeHeader ();
// Write custom data
serializer . writeValue ({ custom: 'data' });
const buffer = serializer . releaseBuffer ();
// Deserialize
const deserializer = new v8 . Deserializer ( buffer );
deserializer . readHeader ();
const value = deserializer . readValue ();
Memory Management
Manual Garbage Collection
# Expose gc() function
node --expose-gc app.js
if ( global . gc ) {
global . gc (); // Force garbage collection
console . log ( 'GC triggered' );
}
Manual GC should only be used for testing and debugging. The V8 garbage collector is highly optimized and usually knows better when to collect.
Monitoring Memory Usage
function monitorMemory () {
const stats = v8 . getHeapStatistics ();
const used = stats . used_heap_size / 1024 / 1024 ;
const total = stats . heap_size_limit / 1024 / 1024 ;
const percent = ( used / total * 100 ). toFixed ( 2 );
console . log ( `Memory: ${ used . toFixed ( 2 ) } MB / ${ total . toFixed ( 2 ) } MB ( ${ percent } %)` );
if ( percent > 90 ) {
console . warn ( '⚠️ High memory usage!' );
}
}
setInterval ( monitorMemory , 5000 );
Write Heap Snapshot
import v8 from 'node:v8' ;
import fs from 'node:fs' ;
// Simple snapshot write
v8 . writeHeapSnapshot ();
// Custom filename
const filename = `heap- ${ Date . now () } .heapsnapshot` ;
v8 . writeHeapSnapshot ( filename );
Cached Data
Script Compilation Caching
import v8 from 'node:v8' ;
import vm from 'node:vm' ;
// Create script with cached data
const script = new vm . Script ( 'console.log("Hello")' );
const cachedData = script . createCachedData ();
// Reuse cached data
const newScript = new vm . Script ( 'console.log("Hello")' , {
cachedData
});
console . log ( 'Cache was used:' , ! newScript . cachedDataRejected );
Version Tag
const tag1 = v8 . cachedDataVersionTag ();
v8 . setFlagsFromString ( '--allow_natives_syntax' );
const tag2 = v8 . cachedDataVersionTag ();
console . log ( 'Tags differ:' , tag1 !== tag2 );
Optimization Status
// Requires --allow-natives-syntax flag
function hotFunction ( a , b ) {
return a + b ;
}
// Warm up function
for ( let i = 0 ; i < 10000 ; i ++ ) {
hotFunction ( i , i + 1 );
}
// Check optimization status (requires natives syntax)
if ( typeof % GetOptimizationStatus === 'function' ) {
console . log ( 'Optimization status:' , % GetOptimizationStatus ( hotFunction ));
}
V8’s TurboFan compiler automatically optimizes hot code paths. Manual optimization hints are rarely needed.
V8 Integration in C++
Accessing V8 APIs
#include <v8.h>
using v8 ::Context;
using v8 ::Isolate;
using v8 ::Local;
using v8 ::String;
using v8 ::Value;
void CreateString ( const v8 :: FunctionCallbackInfo < Value > & args ) {
Isolate * isolate = args . GetIsolate ();
Local < String > str = String :: NewFromUtf8 (
isolate,
"Hello from V8" ,
v8 :: NewStringType ::kNormal
). ToLocalChecked ();
args . GetReturnValue (). Set (str);
}
#include <v8.h>
#include <libplatform/libplatform.h>
int main () {
// Initialize V8
v8 :: V8 :: InitializeICUDefaultLocation ( argv [ 0 ]);
v8 :: V8 :: InitializeExternalStartupData ( argv [ 0 ]);
std ::unique_ptr < v8 ::Platform > platform =
v8 :: platform :: NewDefaultPlatform ();
v8 :: V8 :: InitializePlatform ( platform . get ());
v8 :: V8 :: Initialize ();
// ... use V8 ...
v8 :: V8 :: Dispose ();
v8 :: V8 :: DisposePlatform ();
return 0 ;
}
Startup Snapshot
// Check if startup snapshot is enabled
const { v8 } = process . versions ;
console . log ( 'V8 version:' , v8 );
// Startup snapshot can reduce startup time
// by pre-compiling and caching built-in modules
Best Practices
Monitor Heap Usage Track heap statistics in production to detect memory leaks
Use Appropriate Limits Set --max-old-space-size based on available memory
Analyze Snapshots Use heap snapshots to investigate memory issues
Avoid Manual GC Let V8’s GC work automatically except for debugging
Debugging Memory Issues
Capture Baseline Snapshot
Take a heap snapshot at application startup
Reproduce the Issue
Run the operation suspected of leaking memory
Capture Second Snapshot
Take another snapshot after the operation
Compare Snapshots
Use Chrome DevTools to compare and identify retained objects
C++ Addons Use V8 APIs in native addons
Node.js Internals Understand Node.js C++ architecture
Embedding Embed V8 in applications
V8 Docs Official V8 documentation