{ "type": "module", "source": "doc/api/vm.md", "modules": [ { "textRaw": "VM (Executing JavaScript)", "name": "vm", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The vm module provides APIs for compiling and running code within V8 Virtual\nMachine contexts. The vm module is not a security mechanism. Do\nnot use it to run untrusted code. The term \"sandbox\" is used throughout these\ndocs simply to refer to a separate context, and does not confer any security\nguarantees.

\n

JavaScript code can be compiled and run immediately or\ncompiled, saved, and run later.

\n

A common use case is to run the code in a sandboxed environment.\nThe sandboxed code uses a different V8 Context, meaning that\nit has a different global object than the rest of the code.

\n

One can provide the context by \"contextifying\" a sandbox\nobject. The sandboxed code treats any property in the sandbox like a\nglobal variable. Any changes to global variables caused by the sandboxed\ncode are reflected in the sandbox object.

\n
const vm = require('vm');\n\nconst x = 1;\n\nconst sandbox = { x: 2 };\nvm.createContext(sandbox); // Contextify the sandbox.\n\nconst code = 'x += 40; var y = 17;';\n// `x` and `y` are global variables in the sandboxed environment.\n// Initially, x has the value 2 because that is the value of sandbox.x.\nvm.runInContext(code, sandbox);\n\nconsole.log(sandbox.x); // 42\nconsole.log(sandbox.y); // 17\n\nconsole.log(x); // 1; y is not defined.\n
", "classes": [ { "textRaw": "Class: vm.Script", "type": "class", "name": "vm.Script", "meta": { "added": [ "v0.3.1" ], "changes": [] }, "desc": "

Instances of the vm.Script class contain precompiled scripts that can be\nexecuted in specific sandboxes (or \"contexts\").

", "methods": [ { "textRaw": "script.createCachedData()", "type": "method", "name": "createCachedData", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [] } ], "desc": "

Creates a code cache that can be used with the Script constructor's\ncachedData option. Returns a Buffer. This method may be called at any\ntime and any number of times.

\n
const script = new vm.Script(`\nfunction add(a, b) {\n  return a + b;\n}\n\nconst x = add(1, 2);\n`);\n\nconst cacheWithoutX = script.createCachedData();\n\nscript.runInThisContext();\n\nconst cacheWithX = script.createCachedData();\n
" }, { "textRaw": "script.runInContext(contextifiedSandbox[, options])", "type": "method", "name": "runInContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`contextifiedSandbox` {Object} A [contextified][] object as returned by the `vm.createContext()` method.", "name": "contextifiedSandbox", "type": "Object", "desc": "A [contextified][] object as returned by the `vm.createContext()` method." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." } ], "optional": true } ] } ], "desc": "

Runs the compiled code contained by the vm.Script object within the given\ncontextifiedSandbox and returns the result. Running code does not have access\nto local scope.

\n

The following example compiles code that increments a global variable, sets\nthe value of another global variable, then execute the code multiple times.\nThe globals are contained in the sandbox object.

\n
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = {\n  animal: 'cat',\n  count: 2\n};\n\nconst script = new vm.Script('count += 1; name = \"kitty\";');\n\nconst context = vm.createContext(sandbox);\nfor (let i = 0; i < 10; ++i) {\n  script.runInContext(context);\n}\n\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 12, name: 'kitty' }\n
\n

Using the timeout or breakOnSigint options will result in new event loops\nand corresponding threads being started, which have a non-zero performance\noverhead.

" }, { "textRaw": "script.runInNewContext([sandbox[, options]])", "type": "method", "name": "runInNewContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19016", "description": "The `contextCodeGeneration` option is supported now." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`sandbox` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", "name": "sandbox", "type": "Object", "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created.", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." }, { "textRaw": "`contextName` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", "name": "contextName", "type": "string", "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", "desc": "Human-readable name of the newly created context." }, { "textRaw": "`contextOrigin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", "name": "contextOrigin", "type": "string", "default": "`''`", "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." }, { "textRaw": "`contextCodeGeneration` {Object}", "name": "contextCodeGeneration", "type": "Object", "options": [ { "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", "name": "strings", "type": "boolean", "default": "`true`", "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." }, { "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", "name": "wasm", "type": "boolean", "default": "`true`", "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." } ] } ], "optional": true } ] } ], "desc": "

First contextifies the given sandbox, runs the compiled code contained by\nthe vm.Script object within the created sandbox, and returns the result.\nRunning code does not have access to local scope.

\n

The following example compiles code that sets a global variable, then executes\nthe code multiple times in different contexts. The globals are set on and\ncontained within each individual sandbox.

\n
const util = require('util');\nconst vm = require('vm');\n\nconst script = new vm.Script('globalVar = \"set\"');\n\nconst sandboxes = [{}, {}, {}];\nsandboxes.forEach((sandbox) => {\n  script.runInNewContext(sandbox);\n});\n\nconsole.log(util.inspect(sandboxes));\n\n// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n
" }, { "textRaw": "script.runInThisContext([options])", "type": "method", "name": "runInThisContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." } ], "optional": true } ] } ], "desc": "

Runs the compiled code contained by the vm.Script within the context of the\ncurrent global object. Running code does not have access to local scope, but\ndoes have access to the current global object.

\n

The following example compiles code that increments a global variable then\nexecutes that code multiple times:

\n
const vm = require('vm');\n\nglobal.globalVar = 0;\n\nconst script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });\n\nfor (let i = 0; i < 1000; ++i) {\n  script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000\n
" } ], "signatures": [ { "params": [ { "textRaw": "`code` {string} The JavaScript code to compile.", "name": "code", "type": "string", "desc": "The JavaScript code to compile." }, { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", "name": "filename", "type": "string", "default": "`'evalmachine.'`", "desc": "Specifies the filename used in stack traces produced by this script." }, { "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "lineOffset", "type": "number", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "columnOffset", "type": "number", "default": "`0`", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." }, { "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", "name": "produceCachedData", "type": "boolean", "default": "`false`", "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental API for the `--experimental-modules` flag, and should not be considered stable.", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental API for the `--experimental-modules` flag, and should not be considered stable.", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`module` {vm.SourceTextModule}", "name": "module", "type": "vm.SourceTextModule" }, { "textRaw": "Returns: {Module Namespace Object|vm.SourceTextModule} Returning a `vm.SourceTextModule` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.SourceTextModule", "desc": "Returning a `vm.SourceTextModule` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] } ], "optional": true } ], "desc": "

If options is a string, then it specifies the filename.

\n

Creating a new vm.Script object compiles code but does not run it. The\ncompiled vm.Script can be run later multiple times. The code is not bound to\nany global object; rather, it is bound before each run, just for that run.

" } ] }, { "textRaw": "Class: vm.SourceTextModule", "type": "class", "name": "vm.SourceTextModule", "meta": { "added": [ "v9.6.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

This feature is only available with the --experimental-vm-modules command\nflag enabled.

\n

The vm.SourceTextModule class provides a low-level interface for using\nECMAScript modules in VM contexts. It is the counterpart of the vm.Script\nclass that closely mirrors Source Text Module Records as defined in the\nECMAScript specification.

\n

Unlike vm.Script however, every vm.SourceTextModule object is bound to a\ncontext from its creation. Operations on vm.SourceTextModule objects are\nintrinsically asynchronous, in contrast with the synchronous nature of\nvm.Script objects. With the help of async functions, however, manipulating\nvm.SourceTextModule objects is fairly straightforward.

\n

Using a vm.SourceTextModule object requires four distinct steps:\ncreation/parsing, linking, instantiation, and evaluation. These four steps are\nillustrated in the following example.

\n

This implementation lies at a lower level than the ECMAScript Module\nloader. There is also currently no way to interact with the Loader, though\nsupport is planned.

\n
const vm = require('vm');\n\nconst contextifiedSandbox = vm.createContext({ secret: 42 });\n\n(async () => {\n  // Step 1\n  //\n  // Create a Module by constructing a new `vm.SourceTextModule` object. This\n  // parses the provided source text, throwing a `SyntaxError` if anything goes\n  // wrong. By default, a Module is created in the top context. But here, we\n  // specify `contextifiedSandbox` as the context this Module belongs to.\n  //\n  // Here, we attempt to obtain the default export from the module \"foo\", and\n  // put it into local binding \"secret\".\n\n  const bar = new vm.SourceTextModule(`\n    import s from 'foo';\n    s;\n  `, { context: contextifiedSandbox });\n\n  // Step 2\n  //\n  // \"Link\" the imported dependencies of this Module to it.\n  //\n  // The provided linking callback (the \"linker\") accepts two arguments: the\n  // parent module (`bar` in this case) and the string that is the specifier of\n  // the imported module. The callback is expected to return a Module that\n  // corresponds to the provided specifier, with certain requirements documented\n  // in `module.link()`.\n  //\n  // If linking has not started for the returned Module, the same linker\n  // callback will be called on the returned Module.\n  //\n  // Even top-level Modules without dependencies must be explicitly linked. The\n  // callback provided would never be called, however.\n  //\n  // The link() method returns a Promise that will be resolved when all the\n  // Promises returned by the linker resolve.\n  //\n  // Note: This is a contrived example in that the linker function creates a new\n  // \"foo\" module every time it is called. In a full-fledged module system, a\n  // cache would probably be used to avoid duplicated modules.\n\n  async function linker(specifier, referencingModule) {\n    if (specifier === 'foo') {\n      return new vm.SourceTextModule(`\n        // The \"secret\" variable refers to the global variable we added to\n        // \"contextifiedSandbox\" when creating the context.\n        export default secret;\n      `, { context: referencingModule.context });\n\n      // Using `contextifiedSandbox` instead of `referencingModule.context`\n      // here would work as well.\n    }\n    throw new Error(`Unable to resolve dependency: ${specifier}`);\n  }\n  await bar.link(linker);\n\n  // Step 3\n  //\n  // Instantiate the top-level Module.\n  //\n  // Only the top-level Module needs to be explicitly instantiated; its\n  // dependencies will be recursively instantiated by instantiate().\n\n  bar.instantiate();\n\n  // Step 4\n  //\n  // Evaluate the Module. The evaluate() method returns a Promise with a single\n  // property \"result\" that contains the result of the very last statement\n  // executed in the Module. In the case of `bar`, it is `s;`, which refers to\n  // the default export of the `foo` module, the `secret` we set in the\n  // beginning to 42.\n\n  const { result } = await bar.evaluate();\n\n  console.log(result);\n  // Prints 42.\n})();\n
", "properties": [ { "textRaw": "`dependencySpecifiers` {string[]}", "type": "string[]", "name": "dependencySpecifiers", "desc": "

The specifiers of all dependencies of this module. The returned array is frozen\nto disallow any changes to it.

\n

Corresponds to the [[RequestedModules]] field of\nSource Text Module Records in the ECMAScript specification.

" }, { "textRaw": "`error` {any}", "type": "any", "name": "error", "desc": "

If the module.status is 'errored', this property contains the exception\nthrown by the module during evaluation. If the status is anything else,\naccessing this property will result in a thrown exception.

\n

The value undefined cannot be used for cases where there is not a thrown\nexception due to possible ambiguity with throw undefined;.

\n

Corresponds to the [[EvaluationError]] field of Source Text Module Records\nin the ECMAScript specification.

" }, { "textRaw": "`linkingStatus` {string}", "type": "string", "name": "linkingStatus", "desc": "

The current linking status of module. It will be one of the following values:

\n" }, { "textRaw": "`namespace` {Object}", "type": "Object", "name": "namespace", "desc": "

The namespace object of the module. This is only available after instantiation\n(module.instantiate()) has completed.

\n

Corresponds to the GetModuleNamespace abstract operation in the ECMAScript\nspecification.

" }, { "textRaw": "`status` {string}", "type": "string", "name": "status", "desc": "

The current status of the module. Will be one of:

\n\n

Other than 'errored', this status string corresponds to the specification's\nSource Text Module Record's [[Status]] field. 'errored' corresponds to\n'evaluated' in the specification, but with [[EvaluationError]] set to a\nvalue that is not undefined.

" }, { "textRaw": "`url` {string}", "type": "string", "name": "url", "desc": "

The URL of the current module, as set in the constructor.

" } ], "methods": [ { "textRaw": "module.evaluate([options])", "type": "method", "name": "evaluate", "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is interrupted, an [`Error`][] will be thrown. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is interrupted, an [`Error`][] will be thrown." } ], "optional": true } ] } ], "desc": "

Evaluate the module.

\n

This must be called after the module has been instantiated; otherwise it will\nthrow an error. It could be called also when the module has already been\nevaluated, in which case it will do one of the following two things:

\n\n

This method cannot be called while the module is being evaluated\n(module.status is 'evaluating') to prevent infinite recursion.

\n

Corresponds to the Evaluate() concrete method field of Source Text Module\nRecords in the ECMAScript specification.

" }, { "textRaw": "module.instantiate()", "type": "method", "name": "instantiate", "signatures": [ { "params": [] } ], "desc": "

Instantiate the module. This must be called after linking has completed\n(linkingStatus is 'linked'); otherwise it will throw an error. It may also\nthrow an exception if one of the dependencies does not provide an export the\nparent module requires.

\n

However, if this function succeeded, further calls to this function after the\ninitial instantiation will be no-ops, to be consistent with the ECMAScript\nspecification.

\n

Unlike other methods operating on Module, this function completes\nsynchronously and returns nothing.

\n

Corresponds to the Instantiate() concrete method field of Source Text\nModule Records in the ECMAScript specification.

" }, { "textRaw": "module.link(linker)", "type": "method", "name": "link", "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`linker` {Function}", "name": "linker", "type": "Function", "options": [ { "textRaw": "`specifier` {string} The specifier of the requested module:```js import foo from 'foo'; // ^^^^^ the module specifier ```", "name": "specifier", "type": "string", "desc": "The specifier of the requested module:```js import foo from 'foo'; // ^^^^^ the module specifier ```" }, { "textRaw": "`referencingModule` {vm.SourceTextModule} The `Module` object `link()` is called on.", "name": "referencingModule", "type": "vm.SourceTextModule", "desc": "The `Module` object `link()` is called on." }, { "textRaw": "Returns: {vm.SourceTextModule|Promise}", "name": "return", "type": "vm.SourceTextModule|Promise" } ] } ] } ], "desc": "

Link module dependencies. This method must be called before instantiation, and\ncan only be called once per module.

\n

The function is expected to return a Module object or a Promise that\neventually resolves to a Module object. The returned Module must satisfy the\nfollowing two invariants:

\n\n

If the returned Module's linkingStatus is 'unlinked', this method will be\nrecursively called on the returned Module with the same provided linker\nfunction.

\n

link() returns a Promise that will either get resolved when all linking\ninstances resolve to a valid Module, or rejected if the linker function either\nthrows an exception or returns an invalid Module.

\n

The linker function roughly corresponds to the implementation-defined\nHostResolveImportedModule abstract operation in the ECMAScript\nspecification, with a few key differences:

\n\n

The actual HostResolveImportedModule implementation used during module\ninstantiation is one that returns the modules linked during linking. Since at\nthat point all modules would have been fully linked already, the\nHostResolveImportedModule implementation is fully synchronous per\nspecification.

" } ], "signatures": [ { "params": [ { "textRaw": "`code` {string} JavaScript Module code to parse", "name": "code", "type": "string", "desc": "JavaScript Module code to parse" }, { "textRaw": "`options`", "name": "options", "options": [ { "textRaw": "`url` {string} URL used in module resolution and stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", "name": "url", "type": "string", "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", "desc": "URL used in module resolution and stack traces." }, { "textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in.", "name": "context", "type": "Object", "desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in." }, { "textRaw": "`lineOffset` {integer} Specifies the line number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", "name": "lineOffset", "type": "integer", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this `Module`." }, { "textRaw": "`columnOffset` {integer} Specifies the column number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", "name": "columnOffset", "type": "integer", "default": "`0`", "desc": "Specifies the column number offset that is displayed in stack traces produced by this `Module`." }, { "textRaw": "`initializeImportMeta` {Function} Called during evaluation of this `Module` to initialize the `import.meta`.", "name": "initializeImportMeta", "type": "Function", "desc": "Called during evaluation of this `Module` to initialize the `import.meta`.", "options": [ { "textRaw": "`meta` {import.meta}", "name": "meta", "type": "import.meta" }, { "textRaw": "`module` {vm.SourceTextModule}", "name": "module", "type": "vm.SourceTextModule" } ] }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`module` {vm.SourceTextModule}", "name": "module", "type": "vm.SourceTextModule" }, { "textRaw": "Returns: {Module Namespace Object|vm.SourceTextModule} Returning a `vm.SourceTextModule` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.SourceTextModule", "desc": "Returning a `vm.SourceTextModule` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] } ], "optional": true } ], "desc": "

Creates a new ES Module object.

\n

Properties assigned to the import.meta object that are objects may\nallow the Module to access information outside the specified context, if the\nobject is created in the top level context. Use vm.runInContext() to create\nobjects in a specific context.

\n
const vm = require('vm');\n\nconst contextifiedSandbox = vm.createContext({ secret: 42 });\n\n(async () => {\n  const module = new vm.SourceTextModule(\n    'Object.getPrototypeOf(import.meta.prop).secret = secret;',\n    {\n      initializeImportMeta(meta) {\n        // Note: this object is created in the top context. As such,\n        // Object.getPrototypeOf(import.meta.prop) points to the\n        // Object.prototype in the top context rather than that in\n        // the sandbox.\n        meta.prop = {};\n      }\n    });\n  // Since module has no dependencies, the linker function will never be called.\n  await module.link(() => {});\n  module.instantiate();\n  await module.evaluate();\n\n  // Now, Object.prototype.secret will be equal to 42.\n  //\n  // To fix this problem, replace\n  //     meta.prop = {};\n  // above with\n  //     meta.prop = vm.runInContext('{}', contextifiedSandbox);\n})();\n
" } ] } ], "methods": [ { "textRaw": "vm.compileFunction(code[, params[, options]])", "type": "method", "name": "compileFunction", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Function}", "name": "return", "type": "Function" }, "params": [ { "textRaw": "`code` {string} The body of the function to compile.", "name": "code", "type": "string", "desc": "The body of the function to compile." }, { "textRaw": "`params` {string[]} An array of strings containing all parameters for the function.", "name": "params", "type": "string[]", "desc": "An array of strings containing all parameters for the function.", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `''`.", "name": "filename", "type": "string", "default": "`''`", "desc": "Specifies the filename used in stack traces produced by this script." }, { "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "lineOffset", "type": "number", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "columnOffset", "type": "number", "default": "`0`", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source." }, { "textRaw": "`produceCachedData` {boolean} Specifies whether to produce new cache data. **Default:** `false`.", "name": "produceCachedData", "type": "boolean", "default": "`false`", "desc": "Specifies whether to produce new cache data." }, { "textRaw": "`parsingContext` {Object} The [contextified][] sandbox in which the said function should be compiled in.", "name": "parsingContext", "type": "Object", "desc": "The [contextified][] sandbox in which the said function should be compiled in." }, { "textRaw": "`contextExtensions` {Object[]} An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling. **Default:** `[]`.", "name": "contextExtensions", "type": "Object[]", "default": "`[]`", "desc": "An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling." } ], "optional": true } ] } ], "desc": "

Compiles the given code into the provided context/sandbox (if no context is\nsupplied, the current context is used), and returns it wrapped inside a\nfunction with the given params.

" }, { "textRaw": "vm.createContext([sandbox[, options]])", "type": "method", "name": "createContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19398", "description": "The `sandbox` object can no longer be a function." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19016", "description": "The `codeGeneration` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} contextified sandbox.", "name": "return", "type": "Object", "desc": "contextified sandbox." }, "params": [ { "textRaw": "`sandbox` {Object}", "name": "sandbox", "type": "Object", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`name` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", "name": "name", "type": "string", "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", "desc": "Human-readable name of the newly created context." }, { "textRaw": "`origin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", "name": "origin", "type": "string", "default": "`''`", "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." }, { "textRaw": "`codeGeneration` {Object}", "name": "codeGeneration", "type": "Object", "options": [ { "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", "name": "strings", "type": "boolean", "default": "`true`", "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." }, { "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", "name": "wasm", "type": "boolean", "default": "`true`", "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." } ] } ], "optional": true } ] } ], "desc": "

If given a sandbox object, the vm.createContext() method will prepare\nthat sandbox so that it can be used in calls to\nvm.runInContext() or script.runInContext(). Inside such scripts,\nthe sandbox object will be the global object, retaining all of its existing\nproperties but also having the built-in objects and functions any standard\nglobal object has. Outside of scripts run by the vm module, global variables\nwill remain unchanged.

\n
const util = require('util');\nconst vm = require('vm');\n\nglobal.globalVar = 3;\n\nconst sandbox = { globalVar: 1 };\nvm.createContext(sandbox);\n\nvm.runInContext('globalVar *= 2;', sandbox);\n\nconsole.log(util.inspect(sandbox)); // { globalVar: 2 }\n\nconsole.log(util.inspect(globalVar)); // 3\n
\n

If sandbox is omitted (or passed explicitly as undefined), a new, empty\ncontextified sandbox object will be returned.

\n

The vm.createContext() method is primarily useful for creating a single\nsandbox that can be used to run multiple scripts. For instance, if emulating a\nweb browser, the method can be used to create a single sandbox representing a\nwindow's global object, then run all <script> tags together within the context\nof that sandbox.

\n

The provided name and origin of the context are made visible through the\nInspector API.

" }, { "textRaw": "vm.isContext(sandbox)", "type": "method", "name": "isContext", "meta": { "added": [ "v0.11.7" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`sandbox` {Object}", "name": "sandbox", "type": "Object" } ] } ], "desc": "

Returns true if the given sandbox object has been contextified using\nvm.createContext().

" }, { "textRaw": "vm.runInContext(code, contextifiedSandbox[, options])", "type": "method", "name": "runInContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`code` {string} The JavaScript code to compile and run.", "name": "code", "type": "string", "desc": "The JavaScript code to compile and run." }, { "textRaw": "`contextifiedSandbox` {Object} The [contextified][] object that will be used as the `global` when the `code` is compiled and run.", "name": "contextifiedSandbox", "type": "Object", "desc": "The [contextified][] object that will be used as the `global` when the `code` is compiled and run." }, { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", "name": "filename", "type": "string", "default": "`'evalmachine.'`", "desc": "Specifies the filename used in stack traces produced by this script." }, { "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "lineOffset", "type": "number", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "columnOffset", "type": "number", "default": "`0`", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." }, { "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", "name": "produceCachedData", "type": "boolean", "default": "`false`", "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental API for the `--experimental-modules` flag, and should not be considered stable.", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental API for the `--experimental-modules` flag, and should not be considered stable.", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`module` {vm.SourceTextModule}", "name": "module", "type": "vm.SourceTextModule" }, { "textRaw": "Returns: {Module Namespace Object|vm.SourceTextModule} Returning a `vm.SourceTextModule` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.SourceTextModule", "desc": "Returning a `vm.SourceTextModule` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] } ], "optional": true } ] } ], "desc": "

The vm.runInContext() method compiles code, runs it within the context of\nthe contextifiedSandbox, then returns the result. Running code does not have\naccess to the local scope. The contextifiedSandbox object must have been\npreviously contextified using the vm.createContext() method.

\n

If options is a string, then it specifies the filename.

\n

The following example compiles and executes different scripts using a single\ncontextified object:

\n
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = { globalVar: 1 };\nvm.createContext(sandbox);\n\nfor (let i = 0; i < 10; ++i) {\n  vm.runInContext('globalVar *= 2;', sandbox);\n}\nconsole.log(util.inspect(sandbox));\n\n// { globalVar: 1024 }\n
" }, { "textRaw": "vm.runInNewContext(code[, sandbox[, options]])", "type": "method", "name": "runInNewContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19016", "description": "The `contextCodeGeneration` option is supported now." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`code` {string} The JavaScript code to compile and run.", "name": "code", "type": "string", "desc": "The JavaScript code to compile and run." }, { "textRaw": "`sandbox` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", "name": "sandbox", "type": "Object", "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created.", "optional": true }, { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", "name": "filename", "type": "string", "default": "`'evalmachine.'`", "desc": "Specifies the filename used in stack traces produced by this script." }, { "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "lineOffset", "type": "number", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "columnOffset", "type": "number", "default": "`0`", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." }, { "textRaw": "`contextName` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", "name": "contextName", "type": "string", "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", "desc": "Human-readable name of the newly created context." }, { "textRaw": "`contextOrigin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", "name": "contextOrigin", "type": "string", "default": "`''`", "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." }, { "textRaw": "`contextCodeGeneration` {Object}", "name": "contextCodeGeneration", "type": "Object", "options": [ { "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", "name": "strings", "type": "boolean", "default": "`true`", "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." }, { "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", "name": "wasm", "type": "boolean", "default": "`true`", "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." } ] }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." }, { "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", "name": "produceCachedData", "type": "boolean", "default": "`false`", "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental API for the `--experimental-modules` flag, and should not be considered stable.", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental API for the `--experimental-modules` flag, and should not be considered stable.", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`module` {vm.SourceTextModule}", "name": "module", "type": "vm.SourceTextModule" }, { "textRaw": "Returns: {Module Namespace Object|vm.SourceTextModule} Returning a `vm.SourceTextModule` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.SourceTextModule", "desc": "Returning a `vm.SourceTextModule` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] } ], "optional": true } ] } ], "desc": "

The vm.runInNewContext() first contextifies the given sandbox object (or\ncreates a new sandbox if passed as undefined), compiles the code, runs it\nwithin the context of the created context, then returns the result. Running code\ndoes not have access to the local scope.

\n

If options is a string, then it specifies the filename.

\n

The following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the sandbox.

\n
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = {\n  animal: 'cat',\n  count: 2\n};\n\nvm.runInNewContext('count += 1; name = \"kitty\"', sandbox);\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 3, name: 'kitty' }\n
" }, { "textRaw": "vm.runInThisContext(code[, options])", "type": "method", "name": "runInThisContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`code` {string} The JavaScript code to compile and run.", "name": "code", "type": "string", "desc": "The JavaScript code to compile and run." }, { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", "name": "filename", "type": "string", "default": "`'evalmachine.'`", "desc": "Specifies the filename used in stack traces produced by this script." }, { "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "lineOffset", "type": "number", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "columnOffset", "type": "number", "default": "`0`", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." }, { "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", "name": "produceCachedData", "type": "boolean", "default": "`false`", "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental API for the `--experimental-modules` flag, and should not be considered stable.", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental API for the `--experimental-modules` flag, and should not be considered stable.", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`module` {vm.SourceTextModule}", "name": "module", "type": "vm.SourceTextModule" }, { "textRaw": "Returns: {Module Namespace Object|vm.SourceTextModule} Returning a `vm.SourceTextModule` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.SourceTextModule", "desc": "Returning a `vm.SourceTextModule` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] } ], "optional": true } ] } ], "desc": "

vm.runInThisContext() compiles code, runs it within the context of the\ncurrent global and returns the result. Running code does not have access to\nlocal scope, but does have access to the current global object.

\n

If options is a string, then it specifies the filename.

\n

The following example illustrates using both vm.runInThisContext() and\nthe JavaScript eval() function to run the same code:

\n\n
const vm = require('vm');\nlet localVar = 'initial value';\n\nconst vmResult = vm.runInThisContext('localVar = \"vm\";');\nconsole.log('vmResult:', vmResult);\nconsole.log('localVar:', localVar);\n\nconst evalResult = eval('localVar = \"eval\";');\nconsole.log('evalResult:', evalResult);\nconsole.log('localVar:', localVar);\n\n// vmResult: 'vm', localVar: 'initial value'\n// evalResult: 'eval', localVar: 'eval'\n
\n

Because vm.runInThisContext() does not have access to the local scope,\nlocalVar is unchanged. In contrast, eval() does have access to the\nlocal scope, so the value localVar is changed. In this way\nvm.runInThisContext() is much like an indirect eval() call, e.g.\n(0,eval)('code').

\n

Example: Running an HTTP Server within a VM

\n

When using either script.runInThisContext() or\nvm.runInThisContext(), the code is executed within the current V8 global\ncontext. The code passed to this VM context will have its own isolated scope.

\n

In order to run a simple web server using the http module the code passed to\nthe context must either call require('http') on its own, or have a reference\nto the http module passed to it. For instance:

\n
'use strict';\nconst vm = require('vm');\n\nconst code = `\n((require) => {\n  const http = require('http');\n\n  http.createServer((request, response) => {\n    response.writeHead(200, { 'Content-Type': 'text/plain' });\n    response.end('Hello World\\\\n');\n  }).listen(8124);\n\n  console.log('Server running at http://127.0.0.1:8124/');\n})`;\n\nvm.runInThisContext(code)(require);\n
\n

The require() in the above case shares the state with the context it is\npassed from. This may introduce risks when untrusted code is executed, e.g.\naltering objects in the context in unwanted ways.

" } ], "modules": [ { "textRaw": "What does it mean to \"contextify\" an object?", "name": "what_does_it_mean_to_\"contextify\"_an_object?", "desc": "

All JavaScript executed within Node.js runs within the scope of a \"context\".\nAccording to the V8 Embedder's Guide:

\n
\n

In V8, a context is an execution environment that allows separate, unrelated,\nJavaScript applications to run in a single instance of V8. You must explicitly\nspecify the context in which you want any JavaScript code to be run.

\n
\n

When the method vm.createContext() is called, the sandbox object that is\npassed in (or a newly created object if sandbox is undefined) is associated\ninternally with a new instance of a V8 Context. This V8 Context provides the\ncode run using the vm module's methods with an isolated global environment\nwithin which it can operate. The process of creating the V8 Context and\nassociating it with the sandbox object is what this document refers to as\n\"contextifying\" the sandbox.

", "type": "module", "displayName": "What does it mean to \"contextify\" an object?" }, { "textRaw": "Timeout limitations when using process.nextTick(), Promises, and queueMicrotask()", "name": "timeout_limitations_when_using_process.nexttick(),_promises,_and_queuemicrotask()", "desc": "

Because of the internal mechanics of how the process.nextTick() queue and\nthe microtask queue that underlies Promises are implemented within V8 and\nNode.js, it is possible for code running within a context to \"escape\" the\ntimeout set using vm.runInContext(), vm.runInNewContext(), and\nvm.runInThisContext().

\n

For example, the following code executed by vm.runInNewContext() with a\ntimeout of 5 milliseconds schedules an infinite loop to run after a promise\nresolves. The scheduled loop is never interrupted by the timeout:

\n
const vm = require('vm');\n\nfunction loop() {\n  while (1) console.log(Date.now());\n}\n\nvm.runInNewContext(\n  'Promise.resolve().then(loop);',\n  { loop, console },\n  { timeout: 5 }\n);\n
\n

This issue also occurs when the loop() call is scheduled using\nthe process.nextTick() and queueMicrotask() functions.

\n

This issue occurs because all contexts share the same microtask and nextTick\nqueues.

", "type": "module", "displayName": "Timeout limitations when using process.nextTick(), Promises, and queueMicrotask()" } ], "type": "module", "displayName": "vm" } ] }