启动快照 API
【Startup Snapshot API】
v8.startupSnapshot 接口可用于为自定义启动快照添加序列化和反序列化钩子。
【The v8.startupSnapshot interface can be used to add serialization and
deserialization hooks for custom startup snapshots.】
$ node --snapshot-blob snapshot.blob --build-snapshot entry.js
# This launches a process with the snapshot
$ node --snapshot-blob snapshot.blob 在上面的示例中,entry.js 可以使用 v8.startupSnapshot 接口中的方法来指定在序列化期间如何为自定义对象保存信息,以及在快照反序列化期间如何使用这些信息来同步这些对象。例如,如果 entry.js 包含以下脚本:
【In the example above, entry.js can use methods from the v8.startupSnapshot
interface to specify how to save information for custom objects in the snapshot
during serialization and how the information can be used to synchronize these
objects during deserialization of the snapshot. For example, if the entry.js
contains the following script:】
'use strict';
const fs = require('node:fs');
const zlib = require('node:zlib');
const path = require('node:path');
const assert = require('node:assert');
const v8 = require('node:v8');
class BookShelf {
storage = new Map();
// Reading a series of files from directory and store them into storage.
constructor(directory, books) {
for (const book of books) {
this.storage.set(book, fs.readFileSync(path.join(directory, book)));
}
}
static compressAll(shelf) {
for (const [ book, content ] of shelf.storage) {
shelf.storage.set(book, zlib.gzipSync(content));
}
}
static decompressAll(shelf) {
for (const [ book, content ] of shelf.storage) {
shelf.storage.set(book, zlib.gunzipSync(content));
}
}
}
// __dirname here is where the snapshot script is placed
// during snapshot building time.
const shelf = new BookShelf(__dirname, [
'book1.en_US.txt',
'book1.es_ES.txt',
'book2.zh_CN.txt',
]);
assert(v8.startupSnapshot.isBuildingSnapshot());
// On snapshot serialization, compress the books to reduce size.
v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf);
// On snapshot deserialization, decompress the books.
v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf);
v8.startupSnapshot.setDeserializeMainFunction((shelf) => {
// process.env and process.argv are refreshed during snapshot
// deserialization.
const lang = process.env.BOOK_LANG || 'en_US';
const book = process.argv[1];
const name = `${book}.${lang}.txt`;
console.log(shelf.storage.get(name));
}, shelf); 生成的二进制文件将在启动时打印从快照反序列化的数据,使用已刷新过的启动进程的 process.env 和 process.argv:
【The resulted binary will get print the data deserialized from the snapshot
during start up, using the refreshed process.env and process.argv of
the launched process:】
$ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1
# Prints content of book1.es_ES.txt deserialized from the snapshot. 目前,从用户空间快照反序列化的应用无法再次创建快照,因此这些 API 仅适用于未从用户空间快照反序列化的应用。
【Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot.】