• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const fs = require('node:fs');
4const zlib = require('node:zlib');
5const path = require('node:path');
6const assert = require('node:assert');
7
8const v8 = require('node:v8');
9
10class BookShelf {
11  storage = new Map();
12
13  // Reading a series of files from directory and store them into storage.
14  constructor(directory, books) {
15    for (const book of books) {
16      this.storage.set(book, fs.readFileSync(path.join(directory, book)));
17    };
18  }
19
20  static compressAll(shelf) {
21    for (const [ book, content ] of shelf.storage) {
22      shelf.storage.set(book, zlib.gzipSync(content));
23    }
24  }
25
26  static decompressAll(shelf) {
27    for (const [ book, content ] of shelf.storage) {
28      shelf.storage.set(book, zlib.gunzipSync(content));
29    }
30  }
31}
32
33// __dirname here is where the snapshot script is placed
34// during snapshot building time.
35const shelf = new BookShelf(__dirname, [
36  'book1.en_US.txt',
37  'book1.es_ES.txt',
38  'book2.zh_CN.txt',
39]);
40
41assert(v8.startupSnapshot.isBuildingSnapshot());
42
43// On snapshot serialization, compress the books to reduce size.
44v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf);
45// On snapshot deserialization, decompress the books.
46v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf);
47v8.startupSnapshot.setDeserializeMainFunction((shelf) => {
48  // process.env and process.argv are refreshed during snapshot
49  // deserialization.
50  const lang = process.env.BOOK_LANG || 'en_US';
51  const book = process.argv[1];
52  const name = `${book}.${lang}.txt`;
53  console.error('Reading', name);
54  console.log(shelf.storage.get(name).toString());
55}, shelf);
56
57assert.throws(() => v8.startupSnapshot.setDeserializeMainFunction(() => {
58  assert.fail('unreachable duplicated main function');
59}), {
60  code: 'ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION',
61});
62