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


var code = 'var n = a; x = y;;\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.

Problem courtesy of: Stephan Ahlf


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.

Solution courtesy of: Jeffrey Zhao


Here is how to do it using UglifyJS:

var UglifyJS = require("uglifyjs");
var parsed = UglifyJS.parse(code);
parsed.globals.each(function(g) {console.log(});

You can try this out by running npm install uglifyjs then node in a terminal. Copy and paste the var code = (...); bit from the question, then the code above; here is the result I get:

> parsed.globals.each(function(g) {console.log(});
Discussion courtesy of: DomQ

This recipe can be found in it's original form on Stack Over Flow.