Node.js VM模块

网友投稿 577 2022-05-28

Executing JavaScript

Class: vm.Script

new vm.Script(code, options)

script.runInContext(contextifiedSandbox[, options])

script.runInNewContext([sandbox][, options])

script.runInThisContext([options])

vm.createContext([sandbox])

vm.isContext(sandbox)

vm.runInContext(code, contextifiedSandbox[, options])

vm.runInDebugContext(code)

vm.runInNewContext(code[, sandbox][, options])

vm.runInThisContext(code[, options])

Example: Running an HTTP Server within a VM

What does it mean to “contextify” an object?

Executing JavaScript

执行JavaScript

The vm module provides APIs for compiling and running code within V8 Virtual Machine contexts. It can be accessed using:

vm模块在V8虚拟机上下文中提供了编译和运行代码的API。它可以通过如下方式访问:

const vm = require('vm')

1

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

JavaScript代码可以被编译然后立即运行,或者编译,保存,并且之后运行。

Class: vm.Script

Added in:

Instances of the vm.Script class contain precompiled scripts that can be executed in specific sandboxes (or “contexts”).

vm.Script类的实例包含的预编译脚本可以在沙箱中被执行(或者上下文环境中)。

new vm.Script(code, options)

Added in: v0.3.1

code The JavaScript code to compile.

options

filename Specifies the filename used in stack traces produced by this script.

lineOffset Specifies the line number offset that is displayed in stack traces produced by this script.

columnOffset Specifies the column number offset that is displayed in stack traces produced by this script.

displayErrors When true, if an Error error occurs while compiling the code, the line of code causing the error is attached to the stack trace.

timeout Specifies the number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown.

cachedData Provides an optional Buffer 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.

produceCachedData 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.

code 待编译的JavaScript代码

options 选项

filename 指定这个脚本产生的堆栈跟踪信息所使用的文件名

lineOffset 指定这个脚本产生的堆栈跟踪信息的行号偏移量

columnOffset 指定这个脚本产生的堆栈跟踪信息的列号偏移量

displayErrors 当被设置为真的时候,如果在编译代码时发生了错误,造成错误的行号会被附加到堆栈跟踪信息中。

timeout 指定中断执行前代码执行的最长时间,如果执行被中断,就会抛出一个错误。

cachedData 提供一个可选的V8代码缓冲数据给提供的源使用。当提供该值的时候,cachedDataRejected值将会被设置,要么为真要么为假,取决于V8接受的数据。

produceCachedData 当设置为真,且没有cachedData的时候,V8将会尝试产生代码来缓存原代码的数据。执行成功后,V8代码缓存数据的字节数组就会被生产并存储在返回的vm.Script实例的cachedData属性中。cachedDataProduced 要么设置为真要么设置为假,取决于是否代码还从数据被成功生成。

Creating a new vm.Script object compiles code but does not run it. The compiled vm.Script can be run later multiple times. It is important to note that the code is not bound to any global object; rather, it is bound before each run, just for that run.

创建一个新的vm.Script对象编译代码但是并不运行。编译的vm.Script之后可以被多次运行。必须注意的是该代码并没有绑定到任何的全局对象;相反的它们只在每次运行前被绑定到那次的运行环境上。

script.runInContext(contextifiedSandbox[, options])

Added in: v0.3.1

contextifiedSandbox A contextified object as returned by the vm.createContext() method.

options

filename Specifies the filename used in stack traces produced by this script.

lineOffset Specifies the line number offset that is displayed in stack traces produced by this script.

columnOffset Specifies the column number offset that is displayed in stack traces produced by this script.

displayErrors When true, if an Error error occurs while compiling the code, the line of code causing the error is attached to the stack trace.

timeout Specifies the number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown.

breakOnSigint: 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.

contextifiedSandbox 一个由vm.createContext()函数返回的上下文对象。

options

filename 指定这个脚本产生的堆栈跟踪信息所使用的文件名

lineOffset 指定这个脚本产生的堆栈跟踪信息的行号偏移量

columnOffset 指定这个脚本产生的堆栈跟踪信息的列号偏移量

displayErrors 当被设置为真的时候,如果在编译代码时发生了错误,造成错误的行号会被附加到堆栈跟踪信息中。

timeout 指定中断执行前代码执行的最长时间,如果执行被中断,就会抛出一个错误。

breakOnSigint: 如果为真,当接收到(Ctrl+C)时,执行会被中断。在脚本执行期间,连接到process.on(“SIGINT”)上存在的事件处理程序将会被禁用,但是在这之后脚本会继续工作。如果执行被中断了,就会抛出一个错误。

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

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

运行编译后的在给定的沙箱上下文中被vm.Script对象包含的代码,然后返回其结果。运行的代码无法获取本地变量。

下面的例子编译代码,增加一个全局变量,设置其它全局变量的值,然后多次执行该代码。全局变量被包含在一个沙盒对象中。

const util = require('util'); const vm = require('vm'); const sandbox = { animal: 'cat', count: 2 }; const script = new vm.Script('count += 1; name= "kitty"'); const context = new vm.createContext(sandbox); for(var i = 0; i < 10; i++) { script.runInContext(context); } console.log(util.inspect(sandbox)); //输出 { animal: 'cat', count: 12, name: 'kitty' }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

script.runInNewContext([sandbox][, options])

Added in: v0.3.1

sandbox An object that will be contextified. If undefined, a new object will be created.

options

filename Specifies the filename used in stack traces produced by this script.

lineOffset Specifies the line number offset that is displayed in stack traces produced by this script.

columnOffset Specifies the column number offset that is displayed in stack traces produced by this script.

displayErrors When true, if an Error error occurs while compiling the code, the line of code causing the error is attached to the stack trace.

timeout Specifies the number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown.

sandbox 一个将会变成上下文的对象。如果未定义,就会创建一个新的对象。

options

filename 指定这个脚本产生的堆栈跟踪信息所使用的文件名

lineOffset 指定这个脚本产生的堆栈跟踪信息的行号偏移量

columnOffset 指定这个脚本产生的堆栈跟踪信息的列号偏移量

displayErrors 当被设置为真的时候,如果在编译代码时发生了错误,造成错误的行号会被附加到堆栈跟踪信息中。

timeout 指定中断执行前代码执行的最长时间,如果执行被中断,就会抛出一个错误。

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

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

首先将给定的沙盘上下文化,在创建的沙盘中运行被vm.Script对象编译好的代码,然后返回其结果。运行的代码无法访问本地范围的对象。

下面的例子编译代码,然后设置一个全局变量,然后在不同的上下文中多次执行该代码。全局变量被设置并包含在每一个单独的沙盘中。

const util = require('util'); const vm = require('vm'); const script = new vm.Script('globalVar = "set"'); const sandboxes = [{}, {}, {}]; sandboxes.forEach((sandbox) => { script.runInNewContext(sandbox); }); console.log(util.inspect(sandboxes)); //输出 [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]

1

2

3

4

5

6

7

8

9

10

11

12

script.runInThisContext([options])

Added in: v0.3.1

- options

- filename Specifies the filename used in stack traces produced by this script.

- lineOffset Specifies the line number offset that is displayed in stack traces produced by this script.

- columnOffset Specifies the column number offset that is displayed in stack traces produced by this script.

- displayErrors When true, if an Error error occurs while compiling the code, the line of code causing the error is attached to the stack trace.

- timeout Specifies the number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown.

options

filename 指定这个脚本产生的堆栈跟踪信息所使用的文件名

lineOffset 指定这个脚本产生的堆栈跟踪信息的行号偏移量

columnOffset 指定这个脚本产生的堆栈跟踪信息的列号偏移量

displayErrors 当被设置为真的时候,如果在编译代码时发生了错误,造成错误的行号会被附加到堆栈跟踪信息中。

timeout 指定中断执行前代码执行的最长时间,如果执行被中断,就会抛出一个错误。

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

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

运行被vm.Script包含的含有当前全局对象上下文的编译好的代码。运行的代码不能访问本地变量,但是可以访问当前的全局对象。

下面的例子编译增加一个全局变量的代码,然后多次执行那个代码。

const vm = require('vm'); //是否有加global都是全局变量 global.globalVar = 0; myVar = 0; const script = new vm.Script('globalVar += 1; myVar += 1', {filename: 'myfile.vm'}); for(var i = 0; i < 1000; i++) { script.runInThisContext(); } console.log(globalVar); // 1000 console.log(myVar); // 1000

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

vm.createContext([sandbox])

Added in: v0.3.1

sandbox

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

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

The vm.createContext() method is primarily useful for creating a single sandbox that can be used to run multiple scripts. For instance, if emulating a web browser, the method can be used to create a single sandbox representing a window’s global object, then run all