node/test/fixtures/snapshot/create-worker-and-vm.js
Anna Henningsen 06bb6b42b3 src: add snapshot support for embedder API
Add experimental support for loading snapshots in the embedder API
by adding a public opaque wrapper for our `SnapshotData` struct and
allowing embedders to pass it to the relevant setup functions.
Where applicable, use these helpers to deduplicate existing code
in Node.js’s startup path.

This has shown a 40 % startup performance increase for a real-world
application, even with the somewhat limited current support for
built-in modules.

The documentation includes a note about no guarantees for API or
ABI stability for this feature while it is experimental.

PR-URL: https://github.com/nodejs/node/pull/45888
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
2023-02-03 20:48:22 +00:00

21 lines
578 B
JavaScript

const {
setDeserializeMainFunction,
} = require('v8').startupSnapshot;
const assert = require('assert');
setDeserializeMainFunction(() => {
const vm = require('vm');
const { Worker } = require('worker_threads');
assert.strictEqual(vm.runInNewContext('21+21'), 42);
const worker = new Worker(
'require("worker_threads").parentPort.postMessage({value: 21 + 21})',
{ eval: true });
const messages = [];
worker.on('message', message => messages.push(message));
process.on('beforeExit', () => {
assert.deepStrictEqual(messages, [{value:42}]);
})
});