开发手册 欢迎您!
软件开发者资料库

虚拟机(JavaScript 执行环境) | Node.js

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。Node.js 的包管理器 npm,是全球最大的开源库生态系统。

Node.js v8.x 中文文档


vm (虚拟机)#

稳定性: 2 - 稳定的

vm 模块提供了一系列 API 用于在 V8 虚拟机环境中编译和运行代码。

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

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

One can provide the context by "contextifying" a sandboxobject. The sandboxed code treats any property on the sandbox like aglobal variable. Any changes on global variables caused by the sandboxedcode are reflected in the sandbox object.

const vm = require('vm');const x = 1;const sandbox = { x: 2 };vm.createContext(sandbox); // Contextify the sandbox.const code = 'x += 40; var y = 17;';// x and y are global variables in the sandboxed environment.// Initially, x has the value 2 because that is the value of sandbox.x.vm.runInContext(code, sandbox);console.log(sandbox.x); // 42console.log(sandbox.y); // 17console.log(x); // 1; y is not defined.

注意: vm模块并不是实现代码安全性的一套机制。绝不要试图用其运行未经信任的代码.

Class: vm.Script#

vm.Script类型的实例包含若干预编译的脚本,这些脚本能够在特定的沙箱(或者上下文)中被运行。

new vm.Script(code, options)#

  • code 需要被解析的JavaScript代码
  • options
    • filename 定义供脚本生成的堆栈跟踪信息所使用的文件名
    • lineOffset 定义脚本生成的堆栈跟踪信息所显示的行号偏移
    • columnOffset 定义脚本生成的堆栈跟踪信息所显示的列号偏移
    • displayErrors 当值为真的时候,假如在解析代码的时候发生错误Error,引起错误的行将会被加入堆栈跟踪信息
    • timeout 定义在被终止执行之前此code被允许执行的最大毫秒数。假如执行被终止,将会抛出一个错误[Error][]。
    • cachedData 为源码提供一个可选的存有v8代码缓存数据的Buffer。一旦提供了此Buffer,取决于v8引擎对Buffer中数据的接受状况,cachedDataRejected值将会被设为要么真要么为假。
    • produceCachedData 当值为真且cachedData不存在的时候,v8将会试图为code生成代码缓存数据。一旦成功,一个有V8代码缓存数据的Buffer将会被生成和储存在vm.Script返回的实例的cachedData属性里。取决于代码缓存数据是否被成功生成,cachedDataProduced的值会被设置为true或者false。

创建一个新的vm.Script对象只编译代码但不会执行它。编译过的vm.Script此后可以被多次执行。code是不绑定于任何全局对象的,相反,它仅仅绑定于每次执行它的对象。

script.runInContext(contextifiedSandbox[, options])#