简体   繁体   中英

Running Playwright in Azure Function

I'm trying to run a simple Azure Function that would enter page and generate a PDF depending on what is visible in a browser.

I created a NodeJS 12 Azure Function with Linux Consumption Plan (B1). I set PLAYWRIGHT_BROWSERS_PATH to 0 .

Function code looks like this:

const { chromium } = require("playwright-chromium");

const baseUrl = "http://someurl";
const targetPage = "/action/";

module.exports = async function (context, req) {
    const browser = await chromium.launch();

    const page = await browser.newPage();
    console.log (baseUrl + targetPage + context.bindingData.id)
    await page.goto(baseUrl + targetPage + context.bindingData.id, { waitUntil: 'domcontentloaded' });
    
    await page.emulateMedia({ media: 'print' });
    const result = await page.pdf({ printBackground: true, format: 'letter' });
        
    context.res = {
      body: result,
      headers: { 'Content-Type': "application/pdf" }
    };   

    await page.close();
    await browser.close();
};

package.json

{
  "name": "",
  "version": "",
  "scripts": {
    "start": "func start",
    "test": "echo \"No tests yet...\""
  },
  "description": "",
  "devDependencies": {},
  "dependencies": {
    "playwright-chromium": "1.3.0"
  }
}

and function.json

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get"
      ],
      "route": "route/{id}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

When I check app insights I could found there following error:

Exception while executing function: Functions.PDF Result: Failure
Exception: Worker was unable to load function PDF: 'Error: Cannot find module 'playwright-chromium'
Require stack:
- /home/site/wwwroot/PDF/index.js
- /azure-functions-host/workers/node/worker-bundle.js
- /azure-functions-host/workers/node/dist/src/nodejsWorker.js'
Stack: Error: Cannot find module 'playwright-chromium'
Require stack:
- /home/site/wwwroot/PDF/index.js
- /azure-functions-host/workers/node/worker-bundle.js
- /azure-functions-host/workers/node/dist/src/nodejsWorker.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)
    at Function.Module._load (internal/modules/cjs/loader.js:841:27)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/home/site/wwwroot/PDF/index.js:1:22)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19) 

whereas I don't ignore node_modules I got this one:

Exception while executing function: Functions.PDF Result: Failure
Exception: Error: browserType.launch: Failed to launch chromium because executable doesn't exist at /tmp/.cache/ms-playwright/chromium-792639/chrome-linux/chrome
Try re-installing playwright with "npm install playwright"
Note: use DEBUG=pw:api environment variable and rerun to capture Playwright logs.
Stack: Error: browserType.launch: Failed to launch chromium because executable doesn't exist at /tmp/.cache/ms-playwright/chromium-792639/chrome-linux/chrome
Try re-installing playwright with "npm install playwright"
Note: use DEBUG=pw:api environment variable and rerun to capture Playwright logs.
    at Chromium._launchServer (/home/site/wwwroot/node_modules/playwright-chromium/lib/server/browserType.js:150:19)
    at async Chromium._innerLaunch (/home/site/wwwroot/node_modules/playwright-chromium/lib/server/browserType.js:76:61)
    at async ProgressController.run (/home/site/wwwroot/node_modules/playwright-chromium/lib/progress.js:75:28)
    at async Chromium.launch (/home/site/wwwroot/node_modules/playwright-chromium/lib/server/browserType.js:62:25)
    at async module.exports (/home/site/wwwroot/PDF/index.js:7:21) 

and lastly:

Exception while executing function: Functions.PDF Result: Failure
Exception: TimeoutError: browserType.launch: Timeout 30000ms exceeded.
=========================== logs ===========================
[browser] <launching> /home/site/wwwroot/node_modules/playwright-chromium/.local-browsers/chromium-792639/chrome-linux/chrome --no-sandbox --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=TranslateUI,BlinkGenPropertyTrees,ImprovedCookieControls,SameSiteByDefaultCookies --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --user-data-dir=/tmp/playwright_chromiumdev_profile-cPdg8P --remote-debugging-pipe --headless --hide-scrollbars --mute-audio --no-startup-window
[browser] <launched> pid=171
============================================================
Note: use DEBUG=pw:api environment variable and rerun to capture Playwright logs.
Stack: TimeoutError: browserType.launch: Timeout 30000ms exceeded.
=========================== logs ===========================
[browser] <launching> /home/site/wwwroot/node_modules/playwright-chromium/.local-browsers/chromium-792639/chrome-linux/chrome --no-sandbox --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=TranslateUI,BlinkGenPropertyTrees,ImprovedCookieControls,SameSiteByDefaultCookies --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --user-data-dir=/tmp/playwright_chromiumdev_profile-cPdg8P --remote-debugging-pipe --headless --hide-scrollbars --mute-audio --no-startup-window
[browser] <launched> pid=171
============================================================
Note: use DEBUG=pw:api environment variable and rerun to capture Playwright logs.
    at ProgressController.run (/home/site/wwwroot/node_modules/playwright-chromium/lib/progress.js:71:30)
    at Object.runAbortableTask (/home/site/wwwroot/node_modules/playwright-chromium/lib/progress.js:24:23)
    at Chromium.launch (/home/site/wwwroot/node_modules/playwright-chromium/lib/server/browserType.js:62:42)
    at module.exports (/home/site/wwwroot/PDF/index.js:7:36)
    at WorkerChannel.invocationRequest (/azure-functions-host/workers/node/worker-bundle.js:18518:26)
    at ClientDuplexStream.<anonymous> (/azure-functions-host/workers/node/worker-bundle.js:18324:30)
    at ClientDuplexStream.emit (events.js:315:20)
    at addChunk (_stream_readable.js:295:12)
    at readableAddChunk (_stream_readable.js:271:9)
    at ClientDuplexStream.Readable.push (_stream_readable.js:212:10) 

I also thought that maybe the playwright/puppeteer works fine on Azure Functions (when not using docker deploy) only when using Linux Consumption Plan (dynamic)?

I played with your example for a while and I got the same errors. These are the things I found that made my example work:

It must be Linux . I know that you mentioned that you picked a Linux plan. But I found that in VS Code that part is hidden, and on the Web the default is Windows. This is important because only the Linux plan runs npm install on the server.

在此处输入图片说明

Make sure that you are building on the server . You can find this option in the VS Code Settings:

在此处输入图片说明

Make sure you set the environment variable PLAYWRIGHT_BROWSERS_PATH , before making the publish .

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM