在node.js中,如何以最轻量级的方式检查给定的代码字符串在语法上是否正确? [英] In node.js, How do you check whether a given string of code is syntactically correct in the most lightweight way?
问题描述
想象一下,我接受来自用户的一段代码,并且想要检查给定的字符串是否是有效的JS?仅从语法角度来看。
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.
我不希望解决方案 eval
,因为当给定代码'x'在语法错误时整个nodejs进程都会出现语法错误。
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.
推荐答案
不要使用 eval
,这与将服务器的控制权移交给公共互联网完全相同。任何人都可以对您的服务器做任何事情 - 删除文件,泄漏文件,发送垃圾邮件等等。令我感到震惊的是,当我注意到它时,答案已收到3个upvotes。
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.
只需使用像esprima这样的Javascript解析器 http://esprima.org/
Just use a Javascript parser like esprima http://esprima.org/
这是一个语法验证器示例,它甚至可以收集多个错误:< a href =https://github.com/ariya/esprima/blob/master/demo/validate.js#L21-L41\"rel =noreferrer> https://github.com/ariya/esprima/blob/ master / demo / validate.js#L21-L41
Here is a syntax validator example it can even collect multiple errors: https://github.com/ariya/esprima/blob/master/demo/validate.js#L21-L41
这篇关于在node.js中,如何以最轻量级的方式检查给定的代码字符串在语法上是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!