{ "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 enables 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.
JavaScript code can be compiled and run immediately or\ncompiled, saved, and run later.
\nA common use case is to run the code in a different V8 Context. This means\ninvoked code has a different global object than the invoking code.
\nOne can provide the context by contextifying an\nobject. The invoked code treats any property in the context like a\nglobal variable. Any changes to global variables caused by the invoked\ncode are reflected in the context object.
\nconst vm = require('vm');\n\nconst x = 1;\n\nconst context = { x: 2 };\nvm.createContext(context); // Contextify the object.\n\nconst code = 'x += 40; var y = 17;';\n// `x` and `y` are global variables in the context.\n// Initially, x has the value 2 because that is the value of context.x.\nvm.runInContext(code, context);\n\nconsole.log(context.x); // 42\nconsole.log(context.y); // 17\n\nconsole.log(x); // 1; y is not defined.\n
",
"modules": [
{
"textRaw": "Class: `vm.Script`",
"name": "class:_`vm.script`",
"meta": {
"added": [
"v0.3.1"
],
"changes": []
},
"desc": "Instances of the vm.Script
class contain precompiled scripts that can be\nexecuted in specific contexts.
code
<string> The JavaScript code to compile.filename
<string> Specifies the filename used in stack traces produced\nby this script. Default: 'evalmachine.<anonymous>'
.lineOffset
<number> Specifies the line number offset that is displayed\nin stack traces produced by this script. Default: 0
.columnOffset
<number> Specifies the column number offset that is displayed\nin stack traces produced by this script. Default: 0
.cachedData
<Buffer> | <TypedArray> | <DataView> Provides an optional Buffer
or\nTypedArray
, or DataView
with V8's code cache data for the supplied\nsource. When supplied, the cachedDataRejected
value will be set to\neither true
or false
depending on acceptance of the data by V8.produceCachedData
<boolean> When true
and no cachedData
is present, V8\nwill attempt to produce code cache data for code
. Upon success, a\nBuffer
with V8's code cache data will be produced and stored in the\ncachedData
property of the returned vm.Script
instance.\nThe cachedDataProduced
value will be set to either true
or false
\ndepending on whether code cache data is produced successfully.\nThis option is deprecated in favor of script.createCachedData()
.\nDefault: false
.importModuleDynamically
<Function> Called during evaluation of this module\nwhen import()
is called. If this option is not specified, calls to\nimport()
will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING
.\nThis option is part of the experimental API for the --experimental-modules
\nflag, and should not be considered stable.
specifier
<string> specifier passed to import()
module
<vm.Module>vm.Module
is\nrecommended in order to take advantage of error tracking, and to avoid\nissues with namespaces that contain then
function exports.If options
is a string, then it specifies the filename.
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.
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.
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
",
"type": "module",
"displayName": "`script.createCachedData()`"
},
{
"textRaw": "`script.runInContext(contextifiedObject[, options])`",
"name": "`script.runincontext(contextifiedobject[,_options])`",
"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."
}
]
},
"desc": "contextifiedObject
<Object> A contextified object as returned by the\nvm.createContext()
method.options
<Object>
displayErrors
<boolean> When true
, if an Error
occurs\nwhile compiling the code
, the line of code causing the error is attached\nto the stack trace. Default: true
.timeout
<integer> Specifies the number of milliseconds to execute code
\nbefore terminating execution. If execution is terminated, an Error
\nwill be thrown. This value must be a strictly positive integer.breakOnSigint
<boolean> If true
, the execution will be terminated when\nSIGINT
(Ctrl+C) is received. Existing handlers for the\nevent that have been attached via process.on('SIGINT')
will be disabled\nduring script execution, but will continue to work after that. If execution\nis terminated, an Error
will be thrown. Default: false
.Runs the compiled code contained by the vm.Script
object within the given\ncontextifiedObject
and returns the result. Running code does not have access\nto local scope.
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 context
object.
const util = require('util');\nconst vm = require('vm');\n\nconst context = {\n animal: 'cat',\n count: 2\n};\n\nconst script = new vm.Script('count += 1; name = \"kitty\";');\n\nvm.createContext(context);\nfor (let i = 0; i < 10; ++i) {\n script.runInContext(context);\n}\n\nconsole.log(util.inspect(context));\n\n// { animal: 'cat', count: 12, name: 'kitty' }\n
\nUsing the timeout
or breakOnSigint
options will result in new event loops\nand corresponding threads being started, which have a non-zero performance\noverhead.
contextObject
<Object> An object that will be contextified. If\nundefined
, a new object will be created.options
<Object>
displayErrors
<boolean> When true
, if an Error
occurs\nwhile compiling the code
, the line of code causing the error is attached\nto the stack trace. Default: true
.timeout
<integer> Specifies the number of milliseconds to execute code
\nbefore terminating execution. If execution is terminated, an Error
\nwill be thrown. This value must be a strictly positive integer.breakOnSigint
<boolean> If true
, the execution will be terminated when\nSIGINT
(Ctrl+C) is received. Existing handlers for the\nevent that have been attached via process.on('SIGINT')
will be disabled\nduring script execution, but will continue to work after that. If execution\nis terminated, an Error
will be thrown. Default: false
.contextName
<string> Human-readable name of the newly created context.\nDefault: 'VM Context i'
, where i
is an ascending numerical index of\nthe created context.contextOrigin
<string> Origin corresponding to the newly\ncreated context for display purposes. The origin should be formatted like a\nURL, but with only the scheme, host, and port (if necessary), like the\nvalue of the url.origin
property of a URL
object. Most notably,\nthis string should omit the trailing slash, as that denotes a path.\nDefault: ''
.contextCodeGeneration
<Object>
First contextifies the given contextObject
, runs the compiled code contained\nby the vm.Script
object within the created context, and returns the result.\nRunning code does not have access to local scope.
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 context
.
const util = require('util');\nconst vm = require('vm');\n\nconst script = new vm.Script('globalVar = \"set\"');\n\nconst contexts = [{}, {}, {}];\ncontexts.forEach((context) => {\n script.runInNewContext(context);\n});\n\nconsole.log(util.inspect(contexts));\n\n// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n
",
"type": "module",
"displayName": "`script.runInNewContext([contextObject[, options]])`"
},
{
"textRaw": "`script.runInThisContext([options])`",
"name": "`script.runinthiscontext([options])`",
"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."
}
]
},
"desc": "options
<Object>
displayErrors
<boolean> When true
, if an Error
occurs\nwhile compiling the code
, the line of code causing the error is attached\nto the stack trace. Default: true
.timeout
<integer> Specifies the number of milliseconds to execute code
\nbefore terminating execution. If execution is terminated, an Error
\nwill be thrown. This value must be a strictly positive integer.breakOnSigint
<boolean> If true
, the execution will be terminated when\nSIGINT
(Ctrl+C) is received. Existing handlers for the\nevent that have been attached via process.on('SIGINT')
will be disabled\nduring script execution, but will continue to work after that. If execution\nis terminated, an Error
will be thrown. Default: false
.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.
The following example compiles code that increments a global
variable then\nexecutes that code multiple times:
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
",
"type": "module",
"displayName": "`script.runInThisContext([options])`"
}
],
"type": "module",
"displayName": "Class: `vm.Script`"
},
{
"textRaw": "Class: `vm.Module`",
"name": "class:_`vm.module`",
"meta": {
"added": [
"v12.16.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"desc": "This feature is only available with the --experimental-vm-modules
command\nflag enabled.
The vm.Module
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 Module Records as defined in the ECMAScript\nspecification.
Unlike vm.Script
however, every vm.Module
object is bound to a context from\nits creation. Operations on vm.Module
objects are intrinsically asynchronous,\nin contrast with the synchronous nature of vm.Script
objects. With the help\nof async functions, however, manipulating vm.Module
objects is fairly\nstraightforward.
Using a vm.Module
object requires three distinct steps: creation/parsing,\nlinking, and evaluation. These three steps are illustrated in the following\nexample.
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.
\nconst vm = require('vm');\n\nconst contextifiedObject = 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 `contextifiedObject` 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: contextifiedObject });\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 // \"contextifiedObject\" when creating the context.\n export default secret;\n `, { context: referencingModule.context });\n\n // Using `contextifiedObject` 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 // 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
",
"modules": [
{
"textRaw": "`module.dependencySpecifiers`",
"name": "`module.dependencyspecifiers`",
"desc": "The specifiers of all dependencies of this module. The returned array is frozen\nto disallow any changes to it.
\nCorresponds to the [[RequestedModules]]
field of Cyclic Module Records in\nthe ECMAScript specification.
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.
The value undefined
cannot be used for cases where there is not a thrown\nexception due to possible ambiguity with throw undefined;
.
Corresponds to the [[EvaluationError]]
field of Cyclic Module Records\nin the ECMAScript specification.
options
<Object>
timeout
<integer> Specifies the number of milliseconds to evaluate\nbefore terminating execution. If execution is interrupted, an Error
\nwill be thrown. This value must be a strictly positive integer.breakOnSigint
<boolean> If true
, the execution will be terminated when\nSIGINT
(Ctrl+C) is received. Existing handlers for the event that have\nbeen attached via process.on('SIGINT')
will be disabled during script\nexecution, but will continue to work after that. If execution is\ninterrupted, an Error
will be thrown. Default: false
.Evaluate the module.
\nThis must be called after the module has been linked; 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:
\nundefined
if the initial evaluation ended in success (module.status
\nis 'evaluated'
)module.status
is 'errored'
)This method cannot be called while the module is being evaluated\n(module.status
is 'evaluating'
) to prevent infinite recursion.
Corresponds to the Evaluate() concrete method field of Cyclic Module\nRecords in the ECMAScript specification.
", "type": "module", "displayName": "`module.evaluate([options])`" }, { "textRaw": "`module.link(linker)`", "name": "`module.link(linker)`", "desc": "linker
<Function>
specifier
<string> The specifier of the requested module:
import foo from 'foo';\n// ^^^^^ the module specifier\n
\nreferencingModule
<vm.Module> The Module
object link()
is called on.
Returns: <vm.Module> | <Promise>
\nReturns: <Promise>
\nLink module dependencies. This method must be called before evaluation, and\ncan only be called once per module.
\nThe 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:
Module
.status
must not be 'errored'
.If the returned Module
's status
is 'unlinked'
, this method will be\nrecursively called on the returned Module
with the same provided linker
\nfunction.
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
.
The linker function roughly corresponds to the implementation-defined\nHostResolveImportedModule abstract operation in the ECMAScript\nspecification, with a few key differences:
\nThe actual HostResolveImportedModule implementation used during module\nlinking 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.
\nCorresponds to the Link() concrete method field of Cyclic Module\nRecords in the ECMAScript specification.
", "type": "module", "displayName": "`module.link(linker)`" }, { "textRaw": "`module.namespace`", "name": "`module.namespace`", "desc": "The namespace object of the module. This is only available after linking\n(module.link()
) has completed.
Corresponds to the GetModuleNamespace abstract operation in the ECMAScript\nspecification.
", "type": "module", "displayName": "`module.namespace`" }, { "textRaw": "`module.status`", "name": "`module.status`", "desc": "The current status of the module. Will be one of:
\n'unlinked'
: module.link()
has not yet been called.
'linking'
: module.link()
has been called, but not all Promises returned\nby the linker function have been resolved yet.
'linked'
: The module has been linked successfully, and all of its\ndependencies are linked, but module.evaluate()
has not yet been called.
'evaluating'
: The module is being evaluated through a module.evaluate()
on\nitself or a parent module.
'evaluated'
: The module has been successfully evaluated.
'errored'
: The module has been evaluated, but an exception was thrown.
Other than 'errored'
, this status string corresponds to the specification's\nCyclic Module Record's [[Status]]
field. 'errored'
corresponds to\n'evaluated'
in the specification, but with [[EvaluationError]]
set to a\nvalue that is not undefined
.
The identifier of the current module, as set in the constructor.
", "type": "module", "displayName": "`module.identifier`" } ], "type": "module", "displayName": "Class: `vm.Module`" }, { "textRaw": "Class: `vm.SourceTextModule`", "name": "class:_`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.
The vm.SourceTextModule
class provides the Source Text Module Record as\ndefined in the ECMAScript specification.
code
<string> JavaScript Module code to parseoptions
identifier
<string> String used in stack traces.\nDefault: 'vm:module(i)'
where i
is a context-specific ascending\nindex.context
<Object> The contextified object as returned by the\nvm.createContext()
method, to compile and evaluate this Module
in.lineOffset
<integer> Specifies the line number offset that is displayed\nin stack traces produced by this Module
. Default: 0
.columnOffset
<integer> Specifies the column number offset that is\ndisplayed in stack traces produced by this Module
. Default: 0
.initializeImportMeta
<Function> Called during evaluation of this Module
\nto initialize the import.meta
.
meta
<import.meta>module
<vm.SourceTextModule>importModuleDynamically
<Function> Called during evaluation of this module\nwhen import()
is called. If this option is not specified, calls to\nimport()
will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING
.
specifier
<string> specifier passed to import()
module
<vm.Module>vm.Module
is\nrecommended in order to take advantage of error tracking, and to avoid\nissues with namespaces that contain then
function exports.Creates a new SourceTextModule
instance.
Properties assigned to the import.meta
object that are objects may\nallow the module to access information outside the specified context
. Use\nvm.runInContext()
to create objects in a specific context.
const vm = require('vm');\n\nconst contextifiedObject = 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 contextified object.\n meta.prop = {};\n }\n });\n // Since module has no dependencies, the linker function will never be called.\n await module.link(() => {});\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('{}', contextifiedObject);\n})();\n
",
"type": "module",
"displayName": "Constructor: `new vm.SourceTextModule(code[, options])`"
}
],
"type": "module",
"displayName": "Class: `vm.SourceTextModule`"
},
{
"textRaw": "Class: `vm.SyntheticModule`",
"name": "class:_`vm.syntheticmodule`",
"meta": {
"added": [
"v12.16.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"desc": "This feature is only available with the --experimental-vm-modules
command\nflag enabled.
The vm.SyntheticModule
class provides the Synthetic Module Record as\ndefined in the WebIDL specification. The purpose of synthetic modules is to\nprovide a generic interface for exposing non-JavaScript sources to ECMAScript\nmodule graphs.
const vm = require('vm');\n\nconst source = '{ \"a\": 1 }';\nconst module = new vm.SyntheticModule(['default'], function() {\n const obj = JSON.parse(source);\n this.setExport('default', obj);\n});\n\n// Use `module` in linking...\n
",
"modules": [
{
"textRaw": "Constructor: `new vm.SyntheticModule(exportNames, evaluateCallback[, options])`",
"name": "constructor:_`new_vm.syntheticmodule(exportnames,_evaluatecallback[,_options])`",
"meta": {
"added": [
"v12.16.0"
],
"changes": []
},
"desc": "exportNames
<string[]> Array of names that will be exported from the module.evaluateCallback
<Function> Called when the module is evaluated.options
identifier
<string> String used in stack traces.\nDefault: 'vm:module(i)'
where i
is a context-specific ascending\nindex.context
<Object> The contextified object as returned by the\nvm.createContext()
method, to compile and evaluate this Module
in.Creates a new SyntheticModule
instance.
Objects assigned to the exports of this instance may allow importers of\nthe module to access information outside the specified context
. Use\nvm.runInContext()
to create objects in a specific context.
This method is used after the module is linked to set the values of exports. If\nit is called before the module is linked, an ERR_VM_MODULE_STATUS
error\nwill be thrown.
const vm = require('vm');\n\n(async () => {\n const m = new vm.SyntheticModule(['x'], () => {\n m.setExport('x', 1);\n });\n\n await m.link(() => {});\n await m.evaluate();\n\n assert.strictEqual(m.namespace.x, 1);\n})();\n
",
"type": "module",
"displayName": "`syntheticModule.setExport(name, value)`"
}
],
"type": "module",
"displayName": "Class: `vm.SyntheticModule`"
},
{
"textRaw": "`vm.compileFunction(code[, params[, options]])`",
"name": "`vm.compilefunction(code[,_params[,_options]])`",
"meta": {
"added": [
"v10.10.0"
],
"changes": []
},
"desc": "code
<string> The body of the function to compile.params
<string[]> An array of strings containing all parameters for the\nfunction.options
<Object>
filename
<string> Specifies the filename used in stack traces produced\nby this script. Default: ''
.lineOffset
<number> Specifies the line number offset that is displayed\nin stack traces produced by this script. Default: 0
.columnOffset
<number> Specifies the column number offset that is displayed\nin stack traces produced by this script. Default: 0
.cachedData
<Buffer> | <TypedArray> | <DataView> Provides an optional Buffer
or\nTypedArray
, or DataView
with V8's code cache data for the supplied\nsource.produceCachedData
<boolean> Specifies whether to produce new cache data.\nDefault: false
.parsingContext
<Object> The contextified object in which the said\nfunction should be compiled in.contextExtensions
<Object[]> An array containing a collection of context\nextensions (objects wrapping the current scope) to be applied while\ncompiling. Default: []
.Compiles the given code into the provided context (if no context is\nsupplied, the current context is used), and returns it wrapped inside a\nfunction with the given params
.
contextObject
<Object>options
<Object>
name
<string> Human-readable name of the newly created context.\nDefault: 'VM Context i'
, where i
is an ascending numerical index of\nthe created context.origin
<string> Origin corresponding to the newly created\ncontext for display purposes. The origin should be formatted like a URL,\nbut with only the scheme, host, and port (if necessary), like the value of\nthe url.origin
property of a URL
object. Most notably, this\nstring should omit the trailing slash, as that denotes a path.\nDefault: ''
.codeGeneration
<Object>
If given a contextObject
, the vm.createContext()
method will prepare\nthat object so that it can be used in calls to\nvm.runInContext()
or script.runInContext()
. Inside such scripts,\nthe contextObject
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.
const util = require('util');\nconst vm = require('vm');\n\nglobal.globalVar = 3;\n\nconst context = { globalVar: 1 };\nvm.createContext(context);\n\nvm.runInContext('globalVar *= 2;', context);\n\nconsole.log(util.inspect(context)); // { globalVar: 2 }\n\nconsole.log(util.inspect(globalVar)); // 3\n
\nIf contextObject
is omitted (or passed explicitly as undefined
), a new,\nempty contextified object will be returned.
The vm.createContext()
method is primarily useful for creating a single\ncontext that can be used to run multiple scripts. For instance, if emulating a\nweb browser, the method can be used to create a single context representing a\nwindow's global object, then run all <script>
tags together within that\ncontext.
The provided name
and origin
of the context are made visible through the\nInspector API.
Returns true
if the given oject
object has been contextified using\nvm.createContext()
.
code
<string> The JavaScript code to compile and run.contextifiedObject
<Object> The contextified object that will be used\nas the global
when the code
is compiled and run.filename
<string> Specifies the filename used in stack traces produced\nby this script. Default: 'evalmachine.<anonymous>'
.lineOffset
<number> Specifies the line number offset that is displayed\nin stack traces produced by this script. Default: 0
.columnOffset
<number> Specifies the column number offset that is displayed\nin stack traces produced by this script. Default: 0
.displayErrors
<boolean> When true
, if an Error
occurs\nwhile compiling the code
, the line of code causing the error is attached\nto the stack trace. Default: true
.timeout
<integer> Specifies the number of milliseconds to execute code
\nbefore terminating execution. If execution is terminated, an Error
\nwill be thrown. This value must be a strictly positive integer.breakOnSigint
<boolean> If true
, the execution will be terminated when\nSIGINT
(Ctrl+C) is received. Existing handlers for the\nevent that have been attached via process.on('SIGINT')
will be disabled\nduring script execution, but will continue to work after that. If execution\nis terminated, an Error
will be thrown. Default: false
.cachedData
<Buffer> | <TypedArray> | <DataView> Provides an optional Buffer
or\nTypedArray
, or DataView
with V8's code cache data for the supplied\nsource. When supplied, the cachedDataRejected
value will be set to\neither true
or false
depending on acceptance of the data by V8.produceCachedData
<boolean> When true
and no cachedData
is present, V8\nwill attempt to produce code cache data for code
. Upon success, a\nBuffer
with V8's code cache data will be produced and stored in the\ncachedData
property of the returned vm.Script
instance.\nThe cachedDataProduced
value will be set to either true
or false
\ndepending on whether code cache data is produced successfully.\nThis option is deprecated in favor of script.createCachedData()
.\nDefault: false
.importModuleDynamically
<Function> Called during evaluation of this module\nwhen import()
is called. If this option is not specified, calls to\nimport()
will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING
.\nThis option is part of the experimental API for the --experimental-modules
\nflag, and should not be considered stable.
specifier
<string> specifier passed to import()
module
<vm.Module>vm.Module
is\nrecommended in order to take advantage of error tracking, and to avoid\nissues with namespaces that contain then
function exports.The vm.runInContext()
method compiles code
, runs it within the context of\nthe contextifiedObject
, then returns the result. Running code does not have\naccess to the local scope. The contextifiedObject
object must have been\npreviously contextified using the vm.createContext()
method.
If options
is a string, then it specifies the filename.
The following example compiles and executes different scripts using a single\ncontextified object:
\nconst util = require('util');\nconst vm = require('vm');\n\nconst contextObject = { globalVar: 1 };\nvm.createContext(contextObject);\n\nfor (let i = 0; i < 10; ++i) {\n vm.runInContext('globalVar *= 2;', contextObject);\n}\nconsole.log(util.inspect(contextObject));\n\n// { globalVar: 1024 }\n
",
"type": "module",
"displayName": "`vm.runInContext(code, contextifiedObject[, options])`"
},
{
"textRaw": "`vm.runInNewContext(code[, contextObject[, options]])`",
"name": "`vm.runinnewcontext(code[,_contextobject[,_options]])`",
"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."
}
]
},
"desc": "code
<string> The JavaScript code to compile and run.contextObject
<Object> An object that will be contextified. If\nundefined
, a new object will be created.filename
<string> Specifies the filename used in stack traces produced\nby this script. Default: 'evalmachine.<anonymous>'
.lineOffset
<number> Specifies the line number offset that is displayed\nin stack traces produced by this script. Default: 0
.columnOffset
<number> Specifies the column number offset that is displayed\nin stack traces produced by this script. Default: 0
.displayErrors
<boolean> When true
, if an Error
occurs\nwhile compiling the code
, the line of code causing the error is attached\nto the stack trace. Default: true
.timeout
<integer> Specifies the number of milliseconds to execute code
\nbefore terminating execution. If execution is terminated, an Error
\nwill be thrown. This value must be a strictly positive integer.breakOnSigint
<boolean> If true
, the execution will be terminated when\nSIGINT
(Ctrl+C) is received. Existing handlers for the\nevent that have been attached via process.on('SIGINT')
will be disabled\nduring script execution, but will continue to work after that. If execution\nis terminated, an Error
will be thrown. Default: false
.contextName
<string> Human-readable name of the newly created context.\nDefault: 'VM Context i'
, where i
is an ascending numerical index of\nthe created context.contextOrigin
<string> Origin corresponding to the newly\ncreated context for display purposes. The origin should be formatted like a\nURL, but with only the scheme, host, and port (if necessary), like the\nvalue of the url.origin
property of a URL
object. Most notably,\nthis string should omit the trailing slash, as that denotes a path.\nDefault: ''
.contextCodeGeneration
<Object>
cachedData
<Buffer> | <TypedArray> | <DataView> Provides an optional Buffer
or\nTypedArray
, or DataView
with V8's code cache data for the supplied\nsource. When supplied, the cachedDataRejected
value will be set to\neither true
or false
depending on acceptance of the data by V8.produceCachedData
<boolean> When true
and no cachedData
is present, V8\nwill attempt to produce code cache data for code
. Upon success, a\nBuffer
with V8's code cache data will be produced and stored in the\ncachedData
property of the returned vm.Script
instance.\nThe cachedDataProduced
value will be set to either true
or false
\ndepending on whether code cache data is produced successfully.\nThis option is deprecated in favor of script.createCachedData()
.\nDefault: false
.importModuleDynamically
<Function> Called during evaluation of this module\nwhen import()
is called. If this option is not specified, calls to\nimport()
will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING
.\nThis option is part of the experimental API for the --experimental-modules
\nflag, and should not be considered stable.
specifier
<string> specifier passed to import()
module
<vm.Module>vm.Module
is\nrecommended in order to take advantage of error tracking, and to avoid\nissues with namespaces that contain then
function exports.The vm.runInNewContext()
first contextifies the given contextObject
(or\ncreates a new contextObject
if passed as undefined
), compiles the code
,\nruns it within the created context, then returns the result. Running code\ndoes not have access to the local scope.
If options
is a string, then it specifies the filename.
The following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the contextObject
.
const util = require('util');\nconst vm = require('vm');\n\nconst contextObject = {\n animal: 'cat',\n count: 2\n};\n\nvm.runInNewContext('count += 1; name = \"kitty\"', contextObject);\nconsole.log(util.inspect(contextObject));\n\n// { animal: 'cat', count: 3, name: 'kitty' }\n
",
"type": "module",
"displayName": "`vm.runInNewContext(code[, contextObject[, options]])`"
},
{
"textRaw": "`vm.runInThisContext(code[, options])`",
"name": "`vm.runinthiscontext(code[,_options])`",
"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."
}
]
},
"desc": "code
<string> The JavaScript code to compile and run.filename
<string> Specifies the filename used in stack traces produced\nby this script. Default: 'evalmachine.<anonymous>'
.lineOffset
<number> Specifies the line number offset that is displayed\nin stack traces produced by this script. Default: 0
.columnOffset
<number> Specifies the column number offset that is displayed\nin stack traces produced by this script. Default: 0
.displayErrors
<boolean> When true
, if an Error
occurs\nwhile compiling the code
, the line of code causing the error is attached\nto the stack trace. Default: true
.timeout
<integer> Specifies the number of milliseconds to execute code
\nbefore terminating execution. If execution is terminated, an Error
\nwill be thrown. This value must be a strictly positive integer.breakOnSigint
<boolean> If true
, the execution will be terminated when\nSIGINT
(Ctrl+C) is received. Existing handlers for the\nevent that have been attached via process.on('SIGINT')
will be disabled\nduring script execution, but will continue to work after that. If execution\nis terminated, an Error
will be thrown. Default: false
.cachedData
<Buffer> | <TypedArray> | <DataView> Provides an optional Buffer
or\nTypedArray
, or DataView
with V8's code cache data for the supplied\nsource. When supplied, the cachedDataRejected
value will be set to\neither true
or false
depending on acceptance of the data by V8.produceCachedData
<boolean> When true
and no cachedData
is present, V8\nwill attempt to produce code cache data for code
. Upon success, a\nBuffer
with V8's code cache data will be produced and stored in the\ncachedData
property of the returned vm.Script
instance.\nThe cachedDataProduced
value will be set to either true
or false
\ndepending on whether code cache data is produced successfully.\nThis option is deprecated in favor of script.createCachedData()
.\nDefault: false
.importModuleDynamically
<Function> Called during evaluation of this module\nwhen import()
is called. If this option is not specified, calls to\nimport()
will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING
.\nThis option is part of the experimental API for the --experimental-modules
\nflag, and should not be considered stable.
specifier
<string> specifier passed to import()
module
<vm.Module>vm.Module
is\nrecommended in order to take advantage of error tracking, and to avoid\nissues with namespaces that contain then
function exports.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.
If options
is a string, then it specifies the filename.
The following example illustrates using both vm.runInThisContext()
and\nthe JavaScript eval()
function to run the same code:
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
\nBecause 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')
.
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.
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:
'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
\nThe 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.
All JavaScript executed within Node.js runs within the scope of a \"context\".\nAccording to the V8 Embedder's Guide:
\n\n\nIn 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
When the method vm.createContext()
is called, the contextObject
argument\n(or a newly-created object if contextObject
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 contextObject
is what this document refers to as\n\"contextifying\" the object.
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()
.
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:
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
\nThis issue also occurs when the loop()
call is scheduled using\nthe process.nextTick()
and queueMicrotask()
functions.
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" } ] }