Home > Blockchain >  node vm runInContext Unexpected token 'if'
node vm runInContext Unexpected token 'if'

Time:05-04

I've faced a weird error while playing with a VM in node.js

Lemme share a piece of the code, that produces an error:

  const vm = require("VM");

  const context = vm.createContext({result: null});

  const someEvalCode = "if(0==0){0}else{0}";

  const script = new vm.Script(`this.result = ${someEvalCode}`);

  try {
    script.runInContext(context);
  } catch (e) {
    console.log(e.message);
  }

The output:

SyntaxError: Unexpected token 'if'
   at new Script (vm.js:100:7)
   at Object.<anonymous> (/Users/ypetri/Desktop/my files/apps/nodejsApps/helpMeBear/server.js:1995:16)
   at Module._compile (internal/modules/cjs/loader.js:1063:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
   at Module.load (internal/modules/cjs/loader.js:928:32)
   at Function.Module._load (internal/modules/cjs/loader.js:769:14)
   at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
   at internal/main/run_main_module.js:17:47

Any help is appreciated!

CodePudding user response:

Because you can't assign if as statement (this.result = if(0=0){0} else{0} is invalid syntax). Maybe try ternary operator instead:

  const someEvalCode = "0==0 ? 0 : 0";

  const script = new vm.Script(`this.result = ${someEvalCode}`);
  • Related