Skip to content

Commit 4e16ff7

Browse files
committed
[Examples] Add basic JS ESM Node example
1 parent 5edf1e8 commit 4e16ff7

File tree

5 files changed

+186
-0
lines changed

5 files changed

+186
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
API_KEY=YOUR_API_KEY
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Node.js basic JavaScript (ESM) example
2+
3+
## Usage
4+
5+
1. Build module
6+
7+
```bash
8+
cd ../../../ # Navigate to the root folder
9+
deno task npm
10+
```
11+
12+
2. Setup environment variables
13+
14+
- Duplicate `.env.example` and name it `.env`.
15+
- Replace `YOUR_API_KEY` with your SerpApi API key.
16+
17+
3. Install dependencies and run example
18+
19+
```bash
20+
cd examples/node/basic_js_esm
21+
npm i
22+
npm start
23+
```
24+
25+
## Notes
26+
27+
- If you want to run the example without building the module, you can update
28+
`package.json` to depend on the published `serpapi` npm module instead:
29+
```json
30+
{
31+
"type": "module",
32+
"dependencies": {
33+
"dotenv": "*",
34+
"serpapi": "*" // Relies on the npm module
35+
},
36+
"scripts": {
37+
"start": "node example.js"
38+
}
39+
}
40+
```
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import * as Dotenv from "dotenv";
2+
import { config, getJson } from "serpapi";
3+
4+
Dotenv.config();
5+
const apiKey = process.env.API_KEY;
6+
7+
const params = {
8+
q: "Coffee",
9+
api_key: apiKey,
10+
};
11+
12+
// Show result as JSON (async/await)
13+
const response1 = await getJson("google", params);
14+
console.log(response1["organic_results"]);
15+
16+
// Show result as JSON (callback)
17+
getJson("google", params, (json) => console.log(json["organic_results"]));
18+
19+
// Use global config
20+
config.api_key = apiKey;
21+
const response2 = await getJson("google", { q: "Coffee" });
22+
console.log(response2["organic_results"]);

examples/node/basic_js_esm/package-lock.json

Lines changed: 113 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"type": "module",
3+
"dependencies": {
4+
"dotenv": "*",
5+
"serpapi": "../../../npm"
6+
},
7+
"scripts": {
8+
"start": "node example.js"
9+
}
10+
}

0 commit comments

Comments
 (0)