1

I was looking for a way to do some simple scripting in Node JS and discovered the VM module. The documentation specifies that the run* methods return the result of execution, so I thought "Hey, why not just return an object that way and then call on its properties in my main script?"

So I fire up a Node REPL:

$ node
> var vm = require('vm');
undefined
> vm.runInNewContext("{ foo: 'bar' }")
'bar'
> vm.runInNewContext("{ foo: 'bar', baz: 'qux' }")
evalmachine.<anonymous>:1
{ foo: 'bar', baz: 'qux' }
                 ^
SyntaxError: Unexpected token :
>

Not quite the expected results. Interestingly, if I return the result of assignment...

> vm.runInNewContext("exports = { foo: 'bar', baz: 'qux' }")
{ foo: 'bar', baz: 'qux' }

Can someone explain this behavior to me?

Tristan Shelton
  • 327
  • 1
  • 3
  • 15

1 Answers1

3

v8 is interpreting the braces as a code block containing labels. Wrap it in parentheses: vm.runInNewContext("({foo: 'bar', baz: 'qux'})").

ZachB
  • 13,051
  • 4
  • 61
  • 89
  • Thanks! I didn't know that Javascript even had labels.The Node REPL and the Chrome developer console don't exhibit this behavior.. Do they explicitly interpret input as expressions or is there some other trick happening there? – Tristan Shelton Sep 10 '17 at 21:42