Skip to content

SourceTextModule example snippet does not behave as hinted in the docs #64076

Description

@davidebombelli

Affected URL(s)

https://nodejs.org/api/vm.html#new-vmsourcetextmodulecode-options

Description of the problem

I am trying to understand the example snippet:

importvmfrom'node:vm';constcontextifiedObject=vm.createContext({secret: 42});constmodule=newvm.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();awaitmodule.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):1Object.getPrototypeOf(import.meta.prop).secret=secret;^
ReferenceError: secretisnotdefined
at vm:module(0):1:50atSourceTextModule.evaluate(node:internal/vm/module:233:26)
at file:///home/username/test.mjs:19:14atModuleJob.run(node:internal/modules/esm/module_job:439:25)atasync node:internal/modules/esm/loader:646:26atasyncasyncRunEntryPointWithESMLoader(node:internal/modules/run_main:101:5)Node.jsv26.3.0

and if I try to modify meta.prop = {}; with meta.prop = vm.runInContext('{}', contextifiedObject);, I get the error:

vm:module(0):1Object.getPrototypeOf(import.meta.prop).secret=secret;^
TypeError: CannotconvertundefinedornulltoobjectatObject.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

Metadata

Metadata

Assignees

No one assigned

    Labels

    docIssues and PRs related to the documentations.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions