node package manager

node-source-walk

Execute a callback on every node of a source code's AST and stop walking when you see fit

node-source-walk

Execute a callback on every node of a file's AST and stop walking whenever you see fit.

A variation of substack/node-detective and simplification of substack/node-falafel.

npm install node-source-walk

  var Walker = require('node-source-walk');
 
  var walker = new Walker();
 
  // Assume src is the string contents of myfile.js 
  // or the AST of an outside parse of myfile.js 
 
  walker.walk(src, function (node) {
    if (/* some condition */) {
      // No need to keep traversing since we found what we wanted 
      walker.stopWalking();
    }
  });
 

By default, Walker will use babylon (supporting ES6, JSX, Flow, and all other available babylon plugins) and the sourceType: module, but you can change any of the defaults as follows:

var walker = new Walker({
  sourceType: 'script',
  // If you don't like experimental plugins 
  plugins: [
    'jsx',
    'flow'
  ]
});

walk(src, cb)

  • src: the contents of a file OR its (already parsed) AST
  • cb: a function that is called for every visited node

stopWalking()

  • Halts further walking of the AST until another manual call of walk.
  • This is super-beneficial when dealing with large source files

traverse(node, cb)

  • Allows you to traverse an AST node and execute a callback on it
  • Callback should expect the first argument to be an AST node, similar to walk's callback.