Skip to content

Commit a42f336

Browse files
committed
[Examples] Add basic JS CommonJS Node example
1 parent 4e16ff7 commit a42f336

5 files changed

Lines changed: 188 additions & 0 deletions

File tree

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: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Node.js basic JavaScript (CommonJS) 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_commonjs
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+
"dependencies": {
32+
"dotenv": "*",
33+
"serpapi": "*" // Relies on the npm module
34+
},
35+
"scripts": {
36+
"start": "node example.js"
37+
}
38+
}
39+
```
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const Dotenv = require("dotenv");
2+
const { config, getJson } = require("serpapi");
3+
4+
Dotenv.config();
5+
const apiKey = process.env.API_KEY;
6+
7+
const run = async () => {
8+
const params = {
9+
q: "Coffee",
10+
api_key: apiKey,
11+
};
12+
13+
// Show result as JSON (async/await)
14+
const response1 = await getJson("google", params);
15+
console.log(response1["organic_results"]);
16+
17+
// Show result as JSON (callback)
18+
getJson("google", params, (json) => console.log(json["organic_results"]));
19+
20+
// Use global config
21+
config.api_key = apiKey;
22+
const response2 = await getJson("google", { q: "Coffee" });
23+
console.log(response2["organic_results"]);
24+
};
25+
26+
run();

examples/node/basic_js_commonjs/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: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"dependencies": {
3+
"dotenv": "*",
4+
"serpapi": "../../../npm"
5+
},
6+
"scripts": {
7+
"start": "node example.js"
8+
}
9+
}

0 commit comments

Comments
 (0)