Skip to content

Commit cef0d2c

Browse files
doc: add a JS example of find(napiConfig) (#647)
* doc: add a JS example of `find(napiConfig)` * Update js-api.md --------- Co-authored-by: Herrington Darkholme <[email protected]>
1 parent e3e1265 commit cef0d2c

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

website/guide/api-usage/js-api.md

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,23 @@ To try out the JavaScript API, you can use the [code sandbox](https://codesandbo
1111
First, install ast-grep's napi package.
1212

1313
::: code-group
14+
1415
```bash[npm]
1516
npm install --save @ast-grep/napi
1617
```
1718

1819
```bash[pnpm]
1920
pnpm add @ast-grep/napi
2021
```
22+
2123
:::
2224

2325
Now let's explore ast-grep's API!
2426

2527
## Core Concepts
2628

2729
The core concepts in ast-grep's JavaScript API are:
30+
2831
* `SgRoot`: a class representing the whole syntax tree
2932
* `SgNode`: a node in the syntax tree
3033

@@ -133,6 +136,16 @@ Array.isArray(nodes) // true, findAll returns SgNode
133136
nodes.map(n => n.text()) // string array of function source
134137
const empty = root.findAll('not exist') // returns []
135138
empty.length === 0 // true
139+
140+
// find i.e. `console.log("hello world")` using a NapiConfig
141+
const node = root.find({
142+
rule: {
143+
pattern: "console.log($A)"
144+
},
145+
constraints: {
146+
A: { regex: "hello" }
147+
}
148+
})
136149
```
137150

138151
Note, `find` returns `null` if no node is found. `findAll` returns an empty array if nothing matches.
@@ -250,6 +263,7 @@ export class SgNode {
250263
prevAll(): Array<SgNode>
251264
}
252265
```
266+
253267
## Fix code
254268

255269
`SgNode` is immutable so it is impossible to change the code directly.
@@ -294,7 +308,6 @@ See also [ast-grep#1172](https://github.com/ast-grep/ast-grep/issues/1172)
294308

295309
To access other languages, you can use the `parse`/`parseAsync` function and the `Lang` enum.
296310

297-
298311
**Example**
299312

300313
```js

0 commit comments

Comments
 (0)