我可以在 Node 中执行字符串命令吗?

Ken*_*Ken 7 node.js

如果我构造一个存储在字符串变量中的函数或命令列表,有没有办法可以在节点中执行它们并保留另一个变量中返回的内容?IE

var result = executeMyCoolStringCommands(myStringVariableWithCommands);
Run Code Online (Sandbox Code Playgroud)

小智 13

选项-e将允许您将任意文本作为 node.js 源代码运行:

node -e "console.log(JSON.stringify({}))"


Emp*_*pus 6

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)


Sco*_*and 5

当然,我们都知道 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)