Node.js新手求助:serp客户端使用方法及await语法错误解决方案
Hey there! Let's get that error sorted out for you. The message is pretty straightforward—you can only use the await keyword inside an async function, and right now you're calling await serp.search() directly at the top level of your code, which Node.js doesn't allow by default.
Why This Happens
await pauses execution until a promise resolves, but it can't do that in regular synchronous code. Async functions tell JavaScript to expect asynchronous operations, so await works correctly inside them.
Solution 1: Wrap Your Code in an Async Function
The easiest fix is to put your search logic inside an async function, then call that function. I've also added a try/catch block to handle any errors (like network issues or problems with the search request)—this is super important for debugging!
const serp = require("serp"); // Define an async function to hold your search logic async function runGoogleSearch() { const options = { host: "google.fr", qs: { q: "test", filter: 0, pws: 0 }, num: 100 }; try { // Now await works here because we're inside an async function const links = await serp.search(options); console.log("Search results:", links); } catch (error) { // Catch and log any errors that occur during the search console.error("Oops, something went wrong:", error); } } // Call the async function to run your search runGoogleSearch();
Solution 2: Use Top-Level Await (Node.js 14.8+)
If you're using Node.js 14.8 or newer, you can use top-level await without wrapping everything in a function—but you need to use ES modules instead of CommonJS. Here's how:
- Either rename your file to use a
.mjsextension, or add"type": "module"to yourpackage.jsonfile. - Update your code to use
importinstead ofrequire:
// Save as search.mjs or set "type": "module" in package.json import serp from "serp"; const options = { host: "google.fr", qs: { q: "test", filter: 0, pws: 0 }, num: 100 }; try { const links = await serp.search(options); console.log("Search results:", links); } catch (error) { console.error("Oops, something went wrong:", error); }
Quick Tips for New Node.js Developers
- Don't forget to install the serp package first! Run
npm install serpin your project folder before running your code. - Always handle errors with
try/catchwhen working with async operations—this will save you a lot of headaches debugging. - Keep in mind that scraping Google might violate their terms of service, so make sure you're using this tool responsibly.
内容的提问来源于stack exchange,提问作者Patrick Preston

