简体   繁体   中英

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.

What im writing in the console is this:

node main console.log(1+1)

The main.js file is this:

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM