Affected URL(s)
https://nodejs.org/api/vm.html#new-vmsourcetextmodulecode-options
Description of the problem
I am trying to understand the example snippet:
import vm from 'node:vm';
const contextifiedObject = vm.createContext({ secret: 42 });
const module = new vm.SourceTextModule(
'Object.getPrototypeOf(import.meta.prop).secret = secret;',
{
initializeImportMeta(meta) {
// Note: this object is created in the top context. As such,
// Object.getPrototypeOf(import.meta.prop) points to the
// Object.prototype in the top context rather than that in
// the contextified object.
meta.prop = vm.runInContext('{}', contextifiedObject);
},
});
// The module has an empty `moduleRequests` array.
module.linkRequests([]);
module.instantiate();
await module.evaluate();
// Now, Object.prototype.secret will be equal to 42.
//
// To fix this problem, replace
// meta.prop = {};
// above with
// meta.prop = vm.runInContext('{}', contextifiedObject);
According to the comment on line 21, the script should execute and should modify the Object.prototype.secret to be 42. However, when I run the script I get the error:
vm:module(0):1
Object.getPrototypeOf(import.meta.prop).secret = secret;
^
ReferenceError: secret is not defined
at vm:module(0):1:50
at SourceTextModule.evaluate (node:internal/vm/module:233:26)
at file:///home/username/test.mjs:19:14
at ModuleJob.run (node:internal/modules/esm/module_job:439:25)
at async node:internal/modules/esm/loader:646:26
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)
Node.js v26.3.0
and if I try to modify meta.prop = {}; with meta.prop = vm.runInContext('{}', contextifiedObject);, I get the error:
vm:module(0):1
Object.getPrototypeOf(import.meta.prop).secret = secret;
^
TypeError: Cannot convert undefined or null to object
at Object.getPrototypeOf (<anonymous>)
at vm:module(0):1:8
at SourceTextModule.evaluate (node:internal/vm/module:233:26)
at file:///home/username/test.mjs:19:14
at ModuleJob.run (node:internal/modules/esm/module_job:439:25)
at async node:internal/modules/esm/loader:646:26
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)
Node.js v26.3.0
Affected URL(s)
https://nodejs.org/api/vm.html#new-vmsourcetextmodulecode-options
Description of the problem
I am trying to understand the example snippet:
According to the comment on line 21, the script should execute and should modify the
Object.prototype.secretto be 42. However, when I run the script I get the error:and if I try to modify
meta.prop = {};withmeta.prop = vm.runInContext('{}', contextifiedObject);, I get the error: