Using tree-sitter-javascript library, I'm trying to fetch all function names from a Javascript code (in string format) and storing it in a functionNames array.
const Parser = require('tree-sitter');
const JavaScript = require('tree-sitter-javascript');
const parser = new Parser();
parser.setLanguage(JavaScript);
const sourceCode = `function foo() {
console.log('hello world');
}
function bar() {
console.log('bye world');
}`;
const tree = parser.parse(sourceCode);
const functionNames = [];
tree.walk(()=>{
console.log("Node: ", node);
if (node.type === 'function_declaration') {
functionNames.push(node.child(1).text);
}
})
console.log(functionNames);
// Expected output ['foo', 'bar']
// Actual output []
However, the callback to tree.walk() is not executing at all. Nothing gets printed in the log. just an empty array []
What is wrong with this code ? I couldn't find much documentation on this in the official docs (https://github.com/tree-sitter/tree-sitter-javascript)
Is there an alternate way to do this ? Thanks in advance