Node Source Walk AST Traversal

7.0.1 · active · verified Sun Apr 19

node-source-walk is a JavaScript utility library designed for synchronously traversing Abstract Syntax Trees (ASTs) or raw source code strings. It allows developers to apply a callback function to every node within the AST, with the crucial capability to halt the traversal prematurely using `stopWalking()`. The current stable version is 7.0.1. Releases tend to align with Node.js LTS updates, primarily dropping support for older Node.js versions. A key differentiator is its flexibility in supporting both top-down (`walk`, `traverse`) and bottom-up (`moonwalk`) traversals, accepting either source code or a pre-parsed AST, and offering the option to replace its default `@babel/parser` with a custom parser.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate the Walker class, traverse source code, identify specific AST node types (like 'FunctionDeclaration' or 'JSXElement'), and efficiently stop the traversal once a desired node is found. It also shows how to configure the internal parser with custom plugins like 'jsx'.

import Walker from 'node-source-walk';

// Example source code string
const src = `
  const add = (a, b) => a + b;
  function subtract(a, b) {
    return a - b;
  }
  console.log(add(5, 3));
  console.log(subtract(10, 4));
`;

const walker = new Walker();
let foundFunctionDeclaration = false;

console.log('Walking AST for function declarations...');
walker.walk(src, node => {
  if (node.type === 'FunctionDeclaration') {
    console.log(`Found function declaration: ${node.id.name}`);
    foundFunctionDeclaration = true;
    // Stop walking after finding the first one
    walker.stopWalking();
  }
});

if (!foundFunctionDeclaration) {
  console.log('No function declarations found.');
}

// Example with custom parser options (for JSX)
const jsxSrc = `
  import React from 'react';
  function MyComponent() {
    return <div>Hello, JSX!</div>;
  }
`;

const jsxWalker = new Walker({
  plugins: ['jsx'] // Ensure JSX plugin is enabled for parsing
});

console.log('\nWalking AST for JSX elements...');
let foundJsxElement = false;
jsxWalker.walk(jsxSrc, node => {
  if (node.type === 'JSXElement') {
    console.log('Found a JSXElement!');
    foundJsxElement = true;
    jsxWalker.stopWalking();
  }
});

if (!foundJsxElement) {
  console.log('No JSX elements found.');
}

view raw JSON →