Liam Mueller Liam Mueller - 1 year ago 57
Javascript Question

Perfectly fine JavaScript syntax creating error in Eval()

So, I'm creating a very primitive, online interpreter/compiler in Node.js for multiple languages just for the experience and I've run in to a very odd problem when running JS code.

When a user posts, I take their input, escape it a little, and feed it directly into the command line (terrible practice, I know, but I'll be moving to a new system later that doesn't involve direct CMD) This escapes double quotes and \n, \r, etc.

When getting input, I

it with the command (yes, I am giving it a callback, but it's a fairly long one that I don't think is necessary to write)

let parentResults = cp.exec(`node ./builders/${this.builder}.js "${this.escapedCode}"`);
// First parameter represents the builder to run the user input with
// and escaped code is self-explanatory

The builder that handles JS only has one line:

eval(process.argv[2]); // Already somewhat-escaped code

Now, when I write something like

function foo(x) {


I get the correct output in the console of

But when I do something like

let foo = function(x) {


I get an error saying


SyntaxError: Unexpected identifier

The same thing happens when I use arrow syntax as well. I have no clue what could be tripping it up. Any ideas or help?

Answer Source

I think the problem is that you are missing a ; after the } in the second case. Normally it wouldn't be a problem as javascript interprets the \n as the end of the declaration, but you said that you are removing \n, so this is why it fails.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download