How to parse Javascript code in JavaScript to get variable names that are not in the current scope?

advertisements
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.


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.