UNPKG

1.77 kBMarkdownView Raw
1### node-source-walk [![npm](http://img.shields.io/npm/v/node-source-walk.svg)](https://npmjs.org/package/node-source-walk) [![npm](http://img.shields.io/npm/dm/node-source-walk.svg)](https://npmjs.org/package/node-source-walk)
2
3> Execute a callback on every node of a file's AST and stop walking whenever you see fit.
4
5*A variation of [substack/node-detective](https://github.com/substack/node-detective)
6and simplification of [substack/node-falafel](https://github.com/substack/node-falafel).*
7
8`npm install node-source-walk`
9
10### Usage
11
12```javascript
13 var Walker = require('node-source-walk');
14
15 var walker = new Walker();
16
17 // Assume src is the string contents of myfile.js
18 // or the AST of an outside parse of myfile.js
19
20 walker.walk(src, function (node) {
21 if (/* some condition */) {
22 // No need to keep traversing since we found what we wanted
23 walker.stopWalking();
24 }
25 });
26
27```
28
29By default, Walker will use `acorn` supporting ES6 and the `sourceType: module`, but you can change any of the defaults as follows:
30
31```js
32var walker = new Walker({
33 ecmaVersion: 5,
34 sourceType: 'script'
35});
36```
37
38* The supplied options are passed through to the parser, so you can configure it according
39to acorn's documentation: https://github.com/marijnh/acorn
40
41### Public Members
42
43`walk(src, cb)`
44
45* src: the contents of a file OR its AST (via Esprima or Acorn)
46* cb: a function that is called for every visited node
47
48`stopWalking()`
49
50* Halts further walking of the AST until another manual call of `walk`.
51* This is super-beneficial when dealing with large source files
52
53`traverse(node, cb)`
54
55* Allows you to traverse an AST node and execute a callback on it
56* Callback should expect the first argument to be an AST node, similar to `walk`'s callback.