## 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`:

- `nearleyc` compiles grammar files to JavaScript.
- `nearley-test` lets you quickly test a grammar against some input and see the results. It also lets you explore the internal state of nearley’s Earley table, in case you find that interesting.
- `nearley-unparse` inverts a parser into a generator, allowing you to create random strings that match your grammar.
- `nearley-railroad` generates pretty railroad diagrams from your parser. This is mainly helpful for creating documentation, as (for example) on json.org.

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

- Take a look at a nearley tutorial written by @gajus, or a blog post about using nearley-unparse to generate murder mystery plots.
- Read my blog post to learn more about the algorithm.
- Read about Marpa to learn more than you ever thought you wanted to know about parsing.