chevrotain, jison, nearley, and pegjs are JavaScript libraries designed to help developers build parsersβtools that read structured text (like code, config files, or data formats) and turn it into a usable format. While they all solve the same core problem, they use different underlying theories and offer distinct developer experiences. jison is a classic tool based on LALR(1) grammar, similar to Yacc. pegjs uses Parsing Expression Grammars (PEG), focusing on top-down parsing with infinite lookahead. nearley also uses PEG but adds support for probabilistic parsing and near-linear performance. chevrotain takes a unique approach by letting you write parsers in pure JavaScript code rather than a separate grammar syntax, offering high performance and excellent debugging tools.
When you need to read structured textβlike a custom config file, a query language, or even a new programming languageβyou need a parser. The JavaScript ecosystem offers four major tools for this: chevrotain, jison, nearley, and pegjs. While they all turn text into data, they work in very different ways. Choosing the right one depends on your need for speed, error handling, grammar complexity, and how much you want to learn a new syntax.
The biggest difference is how you tell the library what your language looks like.
chevrotain lets you write your parser using standard JavaScript classes and methods. You don't learn a new grammar language; you just write code. This makes it easy to debug because you can set breakpoints in your editor.
// chevrotain: Parser defined in pure JS
class MyParser extends Parser {
constructor(input) {
super(input, [MyLexer]);
this.RULE("expression", () => {
this.SUBRULE(this.term);
this.OPTION(() => {
this.CONSUME(Plus);
this.SUBRULE2(this.term);
});
});
this.performSelfAnalysis();
}
}
jison uses a special grammar syntax based on Yacc/Bison. You write rules in a separate string or file, mixing code blocks inside the grammar definitions.
// jison: Grammar definition string
const parser = new Parser(`
%start expression
%%
expression : expression '+' term { $$ = $1 + $3; }
| term { $$ = $1; }
;
term : number { $$ = $1; }
;
`);
pegjs uses a Parsing Expression Grammar (PEG) syntax. It looks clean and focuses on matching patterns from top to bottom.
// pegjs: PEG grammar string
const parser = peggy.generate(`
expression = head:term tail:("+" @term)* {
return tail.reduce((a, b) => a + b, head);
}
term = [0-9]+ { return parseInt(text()); }
`);
nearley also uses a PEG-style syntax but is more concise and supports advanced features like probabilistic parsing directly in the grammar definition.
// nearley: Grammar file (.ne)
expression -> term (("+" | "-") term):+ {% (data) => data[0].reduce((a, b) => a + b) %}
term -> [0-9]+ {% (data) => parseInt(data[0]) %}
How the parser reads your text affects speed and what kinds of languages it can handle.
chevrotain builds a highly optimized parser that runs extremely fast. Because it's pure JavaScript, it avoids the overhead of interpreting a grammar string at runtime. It is often the fastest option for large inputs.
// chevrotain: High performance via static analysis
const parser = new MyParser(tokenStream);
const result = parser.expression(); // Direct method call, very fast
jison generates a table-driven parser. It is generally fast for valid input but can struggle with complex error recovery. Its LALR(1) strategy means it looks ahead only one token, which limits the kinds of grammars it can parse without conflicts.
// jison: Table-driven execution
const result = parser.parse("1 + 2"); // Uses generated lookup tables
pegjs uses a top-down approach with infinite lookahead. It tries to match rules recursively. This makes it easy to write but can be slower on large inputs or deeply nested structures because it might re-scan the same text multiple times.
// pegjs: Recursive descent
const result = parser.parse("1 + 2"); // May backtrack if rules fail
nearley improves on standard PEG by using a chart parsing algorithm. This gives it near-linear performance even for ambiguous grammars where pegjs would fail or loop forever.
// nearley: Chart parsing for efficiency
const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));
parser.feed("1 + 2");
const result = parser.results[0]; // Handles ambiguity gracefully
When a user makes a typo, how does your parser react? This is critical for tools like IDEs or linters.
chevrotain shines here. It has built-in error recovery strategies. If it finds a mistake, it can skip the bad token and keep going, allowing you to show multiple errors at once instead of stopping at the first one.
// chevrotain: Automatic error recovery
parser.expression();
if (parser.errors.length > 0) {
// Parser found errors but kept going
console.log("Found errors:", parser.errors);
}
jison stops immediately when it hits an error. You can define a custom error handler, but it doesn't naturally support recovering and continuing to parse the rest of the file.
// jison: Stops on first error
try {
parser.parse("1 +"); // Throws exception immediately
} catch (e) {
console.log("Parse failed:", e.message);
}
pegjs also throws an exception when a match fails. It tells you exactly where it got stuck, but it doesn't try to fix the input or continue parsing.
// pegjs: Throws detailed exception
try {
parser.parse("1 +");
} catch (e) {
console.log("Expected number at line", e.location.start.line);
}
nearley behaves similarly to pegjs by default. If the input doesn't match the grammar, it throws an error. However, because it handles ambiguity well, it can sometimes parse inputs that other PEG parsers reject, reducing false errors.
// nearley: Throws if no valid parse tree found
try {
parser.feed("1 +");
if (parser.results.length === 0) throw new Error("No valid parse");
} catch (e) {
console.log("Invalid input");
}
You need to parse code even when it's incomplete or has syntax errors, so you can highlight problems as the user types.
chevrotain// chevrotain: Parse incomplete code safely
const parser = new MyLexerAndParser(incompleteCode);
parser.parse();
// Even with errors, you get a partial AST to highlight
You have a small, well-defined format (like a custom CSS-like config) and want a quick solution.
pegjspegjs is easy to set up.// pegjs: Quick setup for simple formats
const config = parser.parse(`theme: dark; width: 100px;`);
You are designing a new language where some sentences could be interpreted in multiple ways, and you want to explore all possibilities.
nearley// nearley: Handle ambiguous input
parser.feed("ambiguous sentence");
const allInterpretations = parser.results; // Array of all valid trees
You are working on an old project that uses a .jison file for its build process.
jison (only for maintenance)// jison: Legacy compatibility
const oldParser = require('./legacy-grammar.jison');
| Feature | chevrotain | jison | pegjs | nearley |
|---|---|---|---|---|
| Definition Style | Pure JavaScript Code | Yacc/Bison Syntax | PEG Syntax | Concise PEG Syntax |
| Parsing Strategy | Optimized Recursive Descent | LALR(1) Table-Driven | Recursive Descent (PEG) | Chart Parsing (PEG) |
| Error Recovery | β Excellent (Continues parsing) | β Poor (Stops immediately) | β Poor (Stops immediately) | β Poor (Stops immediately) |
| Ambiguity Support | β No | β No | β No | β Yes (Returns all trees) |
| Performance | π Very High | β‘ High | π’ Moderate | β‘ High (for ambiguous) |
| Maintenance Status | β Active | β οΈ Unmaintained | β Active | β Active |
Think about your project's needs:
chevrotain. Its ability to recover from errors is unmatched.pegjs is easy to learn and sufficient for most tasks.nearley is the only choice that handles multiple interpretations well.jison, but plan to migrate away since it is no longer maintained.For most modern frontend architectures requiring custom language support, chevrotain or pegjs will be your go-to tools. Choose chevrotain for power and control, and pegjs for simplicity and speed of development.
Choose chevrotain if you need maximum performance, strong error recovery, and the ability to debug your parser step-by-step. It is ideal for building complex IDE features, linters, or language servers where you need fine-grained control over the parsing process without learning a new grammar syntax.
Avoid jison for new projects as it is largely unmaintained. Only consider it if you are maintaining a legacy codebase that already depends on its specific LALR(1) behavior and migrating to a modern alternative is too costly.
Choose nearley if you need to parse ambiguous grammars (where a sentence could have multiple valid structures) or if you want a concise grammar syntax with powerful features like built-in support for comments and whitespace handling. It is great for experimental languages or data formats with complex rules.
Choose pegjs if you want a simple, well-established PEG parser for standard tasks like parsing configuration files, simple query languages, or data formats where ambiguity is not a concern. It offers a good balance of ease-of-use and performance for most common parsing needs.