Mô-đun máy ảo Node.js

❮ Mô-đun tích hợp


Thí dụ

Chạy một số mã JavaScript trong "máy ảo":

var vm = require('vm');
var myObj = { name: 'John', age: 38 };
vm.createContext(myObj);

vm.runInContext('age += 1;', myObj);

console.log(myObj);

Định nghĩa và Cách sử dụng

Mô-đun VM cung cấp một cách thực thi JavaScript trên máy ảo, gần giống như eval () trong JavaScript.


Cú pháp

Cú pháp để bao gồm mô-đun VM trong ứng dụng của bạn:

var vm = require('vm');

Thuộc tính và phương thức VM

Method Description
createContext() Prepares a virtual machine, or sandbox, where you can execute scripts
isContext() Returns true if the specified sandbox has been created by the createContext() method
runInContext() Executes JavaScript code in the specified context, and returns the result
runInDebug() Executes JavaScript inside the debug context
runInNewContext() Executes JavaScript code in a new context, and returns the result
runInThisContext() Executes JavaScript code in the global context, and returns the result

❮ Mô-đun tích hợp