我试图通过节点控制台发送参数,并希望在eval函数中执行它。
我在控制台中写的是:
node main console.log(1+1)
main.js文件是这样的:
var x = "";
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
x = val;
});
var eval = require('eval')
eval("(" + x + ")");
它抛出了这个错误:
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)
有人知道我做错了什么吗?
我期待在控制台中的输出是:
3
由于
答案 0 :(得分:2)
您需要将console
scope
传递给eval
。例如:
var x = "";
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
x = val;
});
var eval = require('eval')
eval(x, null, 'console');
使用时调用:
node app.js "console.log(1+1)"
输出:
2