Parsing Javascript code and extracting variables and functions
I have some Javascript files, I want to write a tool to extract variables, functions and any other meaningful details.
For example file1.js:
var x = 1;
var y = 2;
function sum(a, b) {
var result = a+b;
return result;
}
So once I analyze this file I would get something similar to:
"vars": [{"name": "x", "value": 1}, {"name": "y", "value": 2}]
"functions": [{"name": "sum", "parameters": ["a", "b"], "vars": [...], "functions": [...]}]
It would be really great if I could narrow the results to scope, so for example "var result" is declared inside sum, I would love to learn about it.
Basically what I'm aiming for is to get as much information as possible from those files and then run some analysis to detect redundancies, etc...
What would be the best way to do this? Should I just write regex to parse those files or are there any decent libraries that would make this easy for me? It doesn't matter which language those libraries are in.
5 comments · 91% upvoted · other discussions
You want to generate an AST and crawl through that to get what you need. See this site for a demo of how that would work http://astexplorer.net/ which uses acorn https://github.com/ternjs/acorn