You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js新手求助:serp客户端使用方法及await语法错误解决方案

Fixing the "await is only valid in async function" Error with the serp Node.js Package

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:

  1. Either rename your file to use a .mjs extension, or add "type": "module" to your package.json file.
  2. Update your code to use import instead of require:
// 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 serp in your project folder before running your code.
  • Always handle errors with try/catch when 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:34:12