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:
- $ npm install esprima
To verify that the module is available, use npm ls
:
- $ npm ls
- /home/ariya/demo
- └── [email protected]
The number after the @
symbol, 4.0.0
, 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:
- $ node
- > var esprima = require('esprima')
- undefined
- > esprima.parseScript('answer = 42')
- Script {
- type: 'Program',
- body: [ ExpressionStatement { type: 'ExpressionStatement', expression: [Object] } ],
- 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:
- $ node
- > var esprima = require('esprima')
- undefined
- > esprima.parseScript('1+')
- 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.