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

寻找无需修改即可运行的Node.js代码示例

Node.js新手的Puppeteer代码报错问题与可靠示例来源

问题背景

我是Node.js新手,但拥有Perl、AppleScript等其他编程语言的丰富经验。自学Node.js过程中,因找不到可直接运行的代码示例而受阻。比如一段Puppeteer代码运行时出现语法错误:

原代码

const puppeteer = require('puppeteer');

// Run in the background (headless mode)
const browser = await puppeteer.launch({ headless: true });

// Navigate to Google
const page = await browser.newPage();
await page.goto('https://google.com');

// Type "JavaScript" into the search bar
await page.evaluate(() => {
  document.querySelector('input[name="q"]').value = 'JavaScript';
});

// Click on the "Google Search" button and wait for the page to load
await Promise.all([
  page.waitForNavigation(),
  page.evaluate(() => {
    document.querySelector('input[value="Google Search"]').click();
  })
]);

// Get all the search result URLs
const links = await page.evaluate(function getUrls() {
  return Array.from(document.querySelectorAll('a cite').values()).
    map(el => el.innerHTML);
});

await browser.close();

运行报错

const browser = await puppeteer.launch({ headless: true });
                ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules

错误修复

报错原因是**await只能在async函数内部或者ES模块的顶级作用域中使用**,原代码直接在顶级作用域使用await,不符合Node.js的语法规则。以下是两种可行的修复方案:

方案1:用自执行async函数包裹代码

这是CommonJS模块(默认的Node.js模块格式)下最通用的解决方式:

const puppeteer = require('puppeteer');

(async () => {
  // Run in the background (headless mode)
  const browser = await puppeteer.launch({ headless: true });

  // Navigate to Google
  const page = await browser.newPage();
  await page.goto('https://google.com');

  // Type "JavaScript" into the search bar
  await page.evaluate(() => {
    document.querySelector('input[name="q"]').value = 'JavaScript';
  });

  // Click on the "Google Search" button and wait for the page to load
  await Promise.all([
    page.waitForNavigation(),
    page.evaluate(() => {
      document.querySelector('input[value="Google Search"]').click();
    })
  ]);

  // Get all the search result URLs
  const links = await page.evaluate(function getUrls() {
    return Array.from(document.querySelectorAll('a cite').values()).
      map(el => el.innerHTML);
  });

  console.log(links); // 新增打印,方便查看结果
  await browser.close();
})();

方案2:切换为ES模块使用顶级await

将代码改为ES模块格式,支持顶级await:

  1. 将文件中的require替换为import
  2. 要么在项目的package.json中添加"type": "module",要么将文件名改为.mjs格式

修改后的代码:

import puppeteer from 'puppeteer';

// Run in the background (headless mode)
const browser = await puppeteer.launch({ headless: true });

// Navigate to Google
const page = await browser.newPage();
await page.goto('https://google.com');

// Type "JavaScript" into the search bar
await page.evaluate(() => {
  document.querySelector('input[name="q"]').value = 'JavaScript';
});

// Click on the "Google Search" button and wait for the page to load
await Promise.all([
  page.waitForNavigation(),
  page.evaluate(() => {
    document.querySelector('input[value="Google Search"]').click();
  })
]);

// Get all the search result URLs
const links = await page.evaluate(function getUrls() {
  return Array.from(document.querySelectorAll('a cite').values()).
    map(el => el.innerHTML);
});

console.log(links);
await browser.close();

可靠的可运行示例来源

  • Node.js官方文档:所有示例均经过验证,覆盖基础语法、异步编程、模块系统等核心内容,版本兼容性标注清晰。
  • Puppeteer官方文档:针对Puppeteer的示例都是可直接运行的,还包含常见场景的最佳实践,避免踩坑。
  • Node.js官方示例仓库:包含CLI工具、Web服务、数据库操作等多种场景的可运行代码,适合快速上手不同方向的开发。
  • 主流框架官方示例:如Express、NestJS等热门Node.js框架的官方仓库中,都有入门级的可运行示例,能快速掌握框架的基础用法。

内容的提问来源于stack exchange,提问作者Todd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:08:17