v8.writeHeapSnapshot([filename[,options]])
filename<string> 要保存 V8 堆快照的文件路径。如果未指定,将生成一个符合模式'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'的文件名,其中{pid}是 Node.js 进程的 PID,{thread_id}在从主 Node.js 线程调用writeHeapSnapshot()时为0,或者为工作线程的 ID。options<Object>- 返回值:<string> 快照保存的文件名。
生成当前 V8 堆的快照并将其写入 JSON 文件。该文件旨在与 Chrome 开发者工具等工具一起使用。JSON 模式未记录,并且特定于 V8 引擎,可能会随着 V8 的不同版本而变化。
【Generates a snapshot of the current V8 heap and writes it to a JSON file. This file is intended to be used with tools such as Chrome DevTools. The JSON schema is undocumented and specific to the V8 engine, and may change from one version of V8 to the next.】
堆快照特定于单个 V8 隔离区。使用 工作线程 时,从主线程生成的堆快照将不包含任何关于工作线程的信息,反之亦然。
【A heap snapshot is specific to a single V8 isolate. When using worker threads, a heap snapshot generated from the main thread will not contain any information about the workers, and vice versa.】
创建堆快照时需要的内存大约是创建快照时堆大小的两倍。这会导致 OOM 杀手可能终止该进程的风险。
【Creating a heap snapshot requires memory about twice the size of the heap at the time the snapshot is created. This results in the risk of OOM killers terminating the process.】
生成快照是一个同步操作,会根据堆大小阻塞事件循环一段时间。
【Generating a snapshot is a synchronous operation which blocks the event loop for a duration depending on the heap size.】
const { writeHeapSnapshot } = require('node:v8');
const {
Worker,
isMainThread,
parentPort,
} = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.once('message', (filename) => {
console.log(`worker heapdump: ${filename}`);
// Now get a heapdump for the main thread.
console.log(`main thread heapdump: ${writeHeapSnapshot()}`);
});
// Tell the worker to create a heapdump.
worker.postMessage('heapdump');
} else {
parentPort.once('message', (message) => {
if (message === 'heapdump') {
// Generate a heapdump for the worker
// and return the filename to the parent.
parentPort.postMessage(writeHeapSnapshot());
}
});
}