Getting started

nearley consists of two components: a compiler and a parser.

The nearley compiler converts grammar definitions from a simple BNF-based syntax to a small JS module. You can then use that module to construct a nearley parser, which parses input strings.

Installation

Both components are published as a single NPM package compatible with Node.js and most browsers.

To use the nearley parser, you need to install nearley locally.

$ npm install --save nearley

To use the nearley compiler, you need to additionally install nearley globally.

$ npm install -g nearley

This actually adds several new commands to your $PATH:

These are documented on the tooling page.

Note: If you’re not ready to install nearley yet, you can follow along in your browser using the nearley playground, an online interface for exploring nearley grammars interactively.

nearley in 3 steps

nearley was written with users in mind: getting started with nearley is as simple as:

Step 1: Describe your grammar using the nearley syntax. In a file called grammar.ne, write:

main -> (statement "\n"):+
statement -> "foo" | "bar"

Step 2: Compile the grammar to a JavaScript module. On the command line, run:

$ nearleyc grammar.ne -o grammar.js

Step 3: Parse some data! In a new JavaScript file, instantiate a Parser object and feed it a string:

const nearley = require("nearley");
const grammar = require("./grammar.js");

// Create a Parser object from our grammar.
const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));

// Parse something!
parser.feed("foo\n");

// parser.results is an array of possible parsings.
console.log(parser.results); // [[[[ "foo" ],"\n" ]]]

What’s next?

Now that you have nearley installed, you can learn how to write a grammar!

Further reading