Node.jsVMモジュール_
例
「仮想マシン」でJavaScriptコードを実行します。
var vm = require('vm');
var myObj = { name: 'John', age: 38 };
vm.createContext(myObj);
vm.runInContext('age += 1;', myObj);
console.log(myObj);
定義と使用法
VMモジュールは、JavaScriptのeval()のように、仮想マシンでJavaScriptを実行する方法を提供します。
構文
アプリケーションにVMモジュールを含めるための構文:
var vm = require('vm');
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 |