如何在 Google 云功能上使用 Apify

How to use Apify on Google Cloud Functions

我正在使用 Apify 作为 Google Cloud Functions 部署一些代码。触发后,云函数会静默终止。我做错了什么?

我有一些使用 Apify 0.15.1 的工作代码。它在本地运行良好。一旦部署为 Google Cloud Functions,它就会静静地失败,没有任何明显的错误。使用 Puppeteer 1.18.1 的等效代码工作正常。

我使用下面更简单的代码重现了这个问题。虽然此示例并不严格要求 Apify,但我希望能够使用 Apify 提供的额外功能。

使用 Apify 的代码:

const Apify = require("apify");

exports.screenshotApify = async (req, res) => {
  let imageBuffer;
  Apify.main(async () => {
    const browser = await Apify.launchPuppeteer({ headless: true });
    const page = await browser.newPage();

    await page.goto("https://xenaccounting.com");

    imageBuffer = await page.screenshot({ fullPage: true });

    await browser.close();
  });

  if (res) {
    res.set("Content-Type", "image/png");
    res.send(imageBuffer);
  }

  return imageBuffer;
};

使用 Puppeteer 的代码:

const puppeteer = require("puppeteer");

exports.screenshotPup = async (req, res) => {
  const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
  const page = await browser.newPage();

  await page.goto("https://xenaccounting.com");

  const imageBuffer = await page.screenshot({ fullpage: true });

  await browser.close();

  if (res) {
    res.set("Content-Type", "image/png");
    res.send(imageBuffer);
  }

  return imageBuffer;
};

一旦部署为 Google Cloud Function(使用 --trigger-http 和 --memory=2048),Puppeteer 变体工作正常,而 Apify 变体静默终止而没有结果(除了 'ok' / HTTP 200 return 值)。

去掉 Apify.main() 函数,它将调用安排到稍后的时间,在您的函数已经返回结果之后。