如果我构造一个存储在字符串变量中的函数或命令列表,有没有办法可以在节点中执行它们并保留另一个变量中返回的内容?IE
var result = executeMyCoolStringCommands(myStringVariableWithCommands);
Run Code Online (Sandbox Code Playgroud)
Node 有非常合适的 VM 模块,它允许您在专用上下文中运行代码。请参阅https://nodejs.org/api/vm.html
例如
const vm = require('vm');
const x = 1;
const context = { x: 2 };
vm.createContext(context); // Contextify the object.
const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the context.
// Initially, x has the value 2 because that is the value of context.x.
vm.runInContext(code, context);
console.log(context.x); // 42
console.log(context.y); // 17
console.log(x); // 1; y is not defined.
Run Code Online (Sandbox Code Playgroud)
当然,我们都知道 using 的弊端eval,但是npm 模块 eval避免使用它,而是执行一个字符串
var _eval = require('eval')
var res = _eval('var x = 123; exports.x = x')
console.log("here is res ", res);
Run Code Online (Sandbox Code Playgroud)
其输出:
here is res { x: 123 }
Run Code Online (Sandbox Code Playgroud)