Imagine that I accept a piece of code from a user and want to just check whether the given string is a valid JS or not? Just from the syntax perspective.
function checkCode(x){
// Logic
}
// returns a boolean, whether 'x' is syntactically right or wrong.
I don't want solutions with eval, since the whole nodejs process gets in to a syntax error when the given code, 'x' is syntactically wrong.
To check a string contains syntactically valid JavaScript without executing it (which would be an incredibly bad idea), you don't need a library, you may use the parser you already have in your JS engine :
try {
new Function(yourString);
// yourString contains syntactically correct JavaScript
} catch(syntaxError) {
// There's an error, you can even display the error to the user
}
Of course this can be done server side.
Check this demonstration
Don't use eval that is literally the same as handing over the control of your server to the public internet. Anyone can do anything with your server - delete files, leak files, send spam email and so on. I am shocked that the answer had received 3 upvotes by the time I noticed it.
Just use a Javascript parser like esprima http://esprima.org/
Here is a syntax validator example it can even collect multiple errors: https://github.com/ariya/esprima/blob/master/demo/validate.js#L21-L41
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With