[英]How can I evaluate console.log(1+2) inside eval()?
Im trying to send a parameter via node console and want to execute it inside eval function. 我试图通过节点控制台发送参数,并想在eval函数中执行它。
What im writing in the console is this: 我在控制台上写的是:
node main console.log(1+1)
The main.js file is this: main.js文件是这样的:
var x = "";
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
x = val;
});
var eval = require('eval')
eval("(" + x + ")");
And it throws this error: 并抛出此错误:
D:\Sandbox\jsdom>node main console.log(1+2)
0: C:\Program Files\nodejs\node.exe
1: D:\Sandbox\jsdom\main
2: console.log(1+2)
evalmachine.<anonymous>:1
(console.log(1+2))
^
ReferenceError: console is not defined
at evalmachine.<anonymous>:1:2
at ContextifyScript.Script.runInContext (vm.js:35:29)
at ContextifyScript.Script.runInNewContext (vm.js:41:15)
at module.exports (D:\Sandbox\jsdom\node_modules\eval\eval.js:69:12)
at Object.<anonymous> (D:\Sandbox\jsdom\main.js:11:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
Does someone know what am I doing wrong? 有人知道我在做什么错吗?
The output that im expecting in console is: 我在控制台中期望的输出是:
3
Thanks 谢谢
You need to pass the console
scope
through to eval
. 您需要将console
scope
传递给eval
。 For example: 例如:
var x = "";
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
x = val;
});
var eval = require('eval')
eval(x, null, 'console');
When called with: 当使用以下命令调用时:
node app.js "console.log(1+1)"
Outputs: 输出:
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.