How to use Apify on Google Cloud Functions

心不动则不痛 提交于 2020-01-30 12:27:57

问题


I'm deploying some code using Apify as Google Cloud Functions. When triggered, the Cloud Function terminates silently. What am I doing wrong?

I have some working code using Apify 0.15.1. It runs fine locally. Once deployed as a Google Cloud Function, it fails silently without any clear error. The equivalent code using Puppeteer 1.18.1 works fine.

I've reproduced the issue using more simple code below. While this example doesn't strictly require Apify, I would like to be able to use the extra functionality provided by Apify.

Code using 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;
};

Code using 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;
};

Once deployed as a Google Cloud Function (with --trigger-http and --memory=2048), the Puppeteer variant works fine, while the Apify variant terminates silently without result (apart from an 'ok' / HTTP 200 return value).


回答1:


Get rid of the Apify.main() function, it schedules the call to a later time, after your function already returned the result.



来源:https://stackoverflow.com/questions/56977763/how-to-use-apify-on-google-cloud-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!