Syntax Delegate
The last argument in the parse
function is a delegate, a callback function invoked for each syntax node (as the node is constructed) with two arguments, the node object itself and the node metadata. The metadata contains the start and end location of the node.
The shortest Node.js script that illustrates the delegate is the following:
- var esprima = require('esprima');
- esprima.parse('answer = 42', {}, function (node) {
- console.log(node.type);
- });
If the script is called delegate.js
, running it with Node.js gives the output:
- $ node delegate.js
- Identifier
- Literal
- AssignmentExpression
- ExpressionStatement
- Program
In the above example, the callback function only does one simple thing: printing the type of the node. The first two calls are with the deepest nodes (which are also leaves), an Identifier node representing answer
and a Literal node for 42
. The next is with an AssignmentExpression node that combines the previous two nodes (answer = 42
). It is then followed by the only statement in the code fragment, an ExpressionStatement node. The last one, as with every syntax tree, is always the top-level Program node.
The order of the nodes being passed as the argument for the callback function resembles a tree traversal using the depth-first algorithm.
If each single-line and multi-line comment must be passed to the callback function as well, the comment
flag in the parsing configuration needs to be true. A modified delegate.js
and its new result (note the addition of LineComment node type):
- $ cat delegate.js
- var esprima = require('esprima');
- esprima.parse('answer = 42 // FIXME', { comment: true }, function (node) {
- console.log(node.type);
- });
- $ node delegate.js
- Identifier
- LineComment
- Literal
- AssignmentExpression
- ExpressionStatement
- Program
The second argument passed to the callback function, the metadata, can be used to locate the node. It is illustrated in the following example:
- $ cat delegate.js
- var esprima = require('esprima');
- esprima.parse('answer = 42', {}, function (node, metadata) {
- console.log(node.type, metadata);
- });
- $ node delegate.js
- Identifier { start: { line: 1, column: 0, offset: 0 },
- end: { line: 1, column: 6, offset: 6 } }
- Literal { start: { line: 1, column: 9, offset: 9 },
- end: { line: 1, column: 11, offset: 11 } }
- AssignmentExpression { start: { line: 1, column: 0, offset: 0 },
- end: { line: 1, column: 11, offset: 11 } }
- ExpressionStatement { start: { line: 1, column: 0, offset: 0 },
- end: { line: 1, column: 11, offset: 11 } }
- Program { start: { line: 1, column: 0, offset: 0 },
- end: { line: 1, column: 11, offset: 11 } }