Estraverse: Accessing grandparent nodes

The “estraverse” library allows you to parse a JavaScript AST (e.g. generated from ESPrima).

When you use it, you pull in a Javascript file, parse it, and then run a set of callbacks over the tree.

The two callbacks you can define are “enter” and “leave” which are called when each node is processed, and when it goes back up the stack past the node.

As a convenience, they give you the parent node in “enter” but typically this isn’t enough – it’s more helpful to have the entire parent chain.

To get this, you can simply make a Javascript array that you tree as a stack, then modify it as the traversal progresses:

const fs = require("fs");
const esprima = require("esprima");
const estraverse = require("estraverse");
const filename = ...

let parentChain = [];

const ast = esprima.parse(
  fs.readFileSync(filename)
);

estraverse.traverse(ast, {
  enter: (node, parent) => {
    parentChain.push(node);
  },
  leave: (node) => {
    parentChain.pop();
  }
});

Leave a Reply

Your email address will not be published. Required fields are marked *