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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Selected as best answer because I felt your answer gave a better explanation as to code's failure before Stuart's edits.
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.)

1 Comment

I couldn't think it could be that easy of a mistake. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.