1

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 child_process.exec 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) {
  console.log(x);
}

foo(5);

I get the correct output in the console of 5.

But when I do something like

let foo = function(x) {
  console.log(x);
}

foo(5);

I get an error saying

console.log(x); 
  ^

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?

Liam Mueller
  • 1,360
  • 2
  • 10
  • 17

2 Answers2

3

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.

Manolo Santos
  • 1,915
  • 1
  • 14
  • 25
  • Selected as best answer because I felt your answer gave a better explanation as to code's failure before Stuart's edits. – Liam Mueller Aug 19 '16 at 17:16
2

It is the missing semicolon in the second example that is tripping it up. It should be:

let foo = function(x) {
  console.log(x);
};

foo(5);

Your builder seems to be removing the newline characters, which would otherwise allow javascript to deal with the absence of a semicolon. (See e.g. here for more explanation on when js can automatically insert a semicolon.)

Community
  • 1
  • 1
Stuart
  • 9,597
  • 1
  • 21
  • 30