Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse Javascript code in Javascript to get variable names not in current scope?

var code = 'var n = a; x = y; status.show();\n// todo: \nconsole.log(xyz, "todo: // tests.", params);';
function parse (c) {
    var myFunc = new Function("myFunc", c); 
}

I'm using V8 NODEJS environment. So maybe it is possible to get information about declared variables and their scope of an existing function?

In fact I need the missing variable names a, x, y, status, xyz and params.
Can anyone point me to the right direction?

Best regards.

like image 700
Stephan Ahlf Avatar asked Dec 15 '22 12:12

Stephan Ahlf


1 Answers

I suggest using some parser like UglifyJS or esprima to parse the code, extract the variables and then test them in the current environment. I don't think that's very difficult to do that since I've built quite some JavaScript code analysis or compilation/evaluation.

But if you need a easier and faster solution, you can also try the JSLint. We can use it as a library, just disable other rules and leave only the "undefined variable". We can test each of the errors in the current environment to see whether they're provided or not.

like image 108
Jeffrey Zhao Avatar answered May 01 '23 14:05

Jeffrey Zhao