In node.js, How do you check whether a given string of code is syntactically correct in the most lightweight way?

喜欢而已 提交于 2019-12-08 17:47:25

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

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

If it's gonna run in the user's browser then you could just eval it there without round-tripping through the server. try/catch should catch the error. Doing it directly will also give feedback to the user quicker.

I already had some code lying around after an experiment. I modified it slightly and put it in a jsfiddle.

Basically just use try/catch:

try {
    eval('Invalid source code');
} catch(e) {
    alert('Error: '+e)
}

Perhaps you can try JSLint.

https://github.com/douglascrockford/JSLint

It's a little bit heavy but it work well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!