Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

🧪Parsing JavaScript Files

Parsing JavaScript Files

The parser module in go-fAST allows you to turn JavaScript source code into a rich, structured Abstract Syntax Tree (AST). This is the foundation for any static analysis, transformation, or introspection you want to perform.


✨ Basic Usage

To parse a JavaScript string into an AST, use the parser.ParseFile() function:

prog, err := parser.ParseFile(src)
if err != nil {
    panic("error parsing src script")
}

If successful, prog will contain an *ast.Program node — the root of your AST.


📂 Example: Parsing a File

package main

import (
	"fmt"
	"os"

	"github.com/t14raptor/go-fast/parser"
)

func main() {
	data, err := os.ReadFile("in.js")
	if err != nil {
		fmt.Println("Failed to read file:", err)
		return
	}

	ast, err := parser.ParseFile(string(data))
	if err != nil {
		fmt.Println("Parsing failed:", err)
		return
	}

	fmt.Println("Successfully parsed AST root:", ast.Type())
	// You can now traverse or transform the AST
}

📦 What You Get

The result of parser.ParseFile() is an *ast.Program, which contains a Body field consisting of a list of statements. This structure mirrors ECMAScript’s source grammar:

Each node in the tree implements the VisitableNode interface, allowing you to use the Visitor API for traversal and analysis.

Last updated