Using Node.js to play with Esprima

To quickly experiment with Esprima, it is recommended to use Node.js and its interactive REPL.

First, install Node.js v4 or later (including its package manager, npm). Then, from the command-line or the terminal, install Esprima npm module:

  1. $ npm install esprima

To verify that the module is available, use npm ls:

  1. $ npm ls
  2. /home/ariya/demo
  3. └── [email protected]

The number after the @ symbol, 3.1.3, indicates the version of Esprima package downloaded and installed from the package registry. This may vary from time to time, depending on the latest stable version available for everyone.

To play with Esprima within Node.js, first launch Node.js. Inside its REPL command prompt, load the module using require and then use it, as illustrated in the following session:

  1. $ node
  2. > var esprima = require('esprima')
  3. undefined
  4. > esprima.parse('answer = 42')
  5. Program {
  6. type: 'Program',
  7. body: [ ExpressionStatement { type: 'ExpressionStatement', expression: [Object] } ],
  8. sourceType: 'script' }

In the above example, the parse function of Esprima is invoked with a string containing a simple JavaScript program. The output is an object (printed by Node.js REPL) that is the representation of the program (an assignment expression). This object follows the format described in details in Appendix A. Syntax Tree Format.

If the source given to Esprima parser is not a valid JavaScript program, an exception will be thrown instead. The following example demonstrates that:

  1. $ node
  2. > var esprima = require('esprima')
  3. undefined
  4. > esprima.parse('1+')
  5. Error: Line 1: Unexpected end of input

To use Esprima in a library or an application designed to be used with Node.js, include esprima as a dependency in the package.json manifest.