Skip to content

Weird issues when passing object literals to eval() or vm.runInNewContext() #19580

@aetheryx

Description

@aetheryx
  • Version: v9.8.0
  • Platform: archlinux 4.14.15-1-ARCH SMP PREEMPT x86_64 GNU/Linux
  • Subsystem: vm, eval

Passing an object literal to eval or vm.runInNewContext (and presumably other vm.run* functions) has weird issues.
When passing an object with one key, the returned value is the value of that key.
Passing an object with two keys throws a SyntaxError even though the passed code is syntactically correct.
Examples:

const output = eval('{ foo: "bar" }');
output === 'bar'; // true
const output = eval('{ foo: "bar", baz: "qux" }');
// Throws a SyntaxError:
// { foo: "bar", baz: "qux" }
//                 ^
// SyntaxError: Unexpected token :

The same issue occurs with vm.runInNewContext:

const vm = require('vm');
const output = vm.runInNewContext('{ foo: "bar" }');
output === 'bar'; // true

vm.runInNewContext('{ foo: "bar", baz: "qux" }');
// Throws a SyntaxError:
// { foo: "bar", baz: "qux" }
//                 ^
// SyntaxError: Unexpected token :

I suspect it to be a parsing error with object literals in this form. For example, this works fine:

const output = eval('const myObj = { foo: "bar" }; myObj;');
output instanceof Object && output.foo === 'bar'; // true

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionIssues that look for answers.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions