I want to get all function and variable declarations made in a Javascript code. I use esprima and I wonder if there is script that I can use for my goal?
For example we have this code:
var myVar1;
var myVar2;
function myTestFunction(funcVar1, funcVar2) {
var myVar3;
}
What I except:
Array with variables
["myVar1", "myVar2"]
And an array with functions:
[{"name": "myTestFuncttion", "params":["funcVar1", "funcVar2"], "variables": ["myVar3"]}]
Any ideas how to achieve this?
Complete solution with fiddle:
Here is some JavaScript code for a test-run:
I'm assuming that this is the desired output:
The lists are flat and the anonymous functions within ddddd are being ignored (they are FunctionExpressions not FunctionDeclarations). Guessing that this is how you want it.
Here is the code - probably / hopefully easy to understand without further explanation:
for testing, you can type
You can also use the estraverse package, it's available on github. Then, essentially, the function visitEachAstNode should be replaced by estraverse.traverse, and otherwise you can leave the code unchanged.
fiddle