javascript - 在 Azure 函数中运行 Playwright

标签 javascript node.js azure azure-functions playwright

我正在尝试运行一个简单的 Azure 函数,该函数将输入页面并根据浏览器中可见的内容生成 PDF。

我使用 Linux 消费计划 (B1) 创建了 NodeJS 12 Azure Function。我将 PLAYWRIGHT_BROWSERS_PATH 设置为 0

函数代码如下所示:

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"
  }
}

和 function.json

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

当我检查应用洞察时,我发现存在以下错误:

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) 

虽然我不会忽略node_modules,但我得到了这个:

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) 

最后:

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) 

我还认为,也许剧作家/傀儡师只有在使用 Linux 消耗计划(动态)时才能在 Azure Functions(不使用 docker 部署时)上正常工作?

最佳答案

我用你的例子玩了一段时间,也遇到了同样的错误。我发现这些是使我的示例发挥作用的因素:

必须是 Linux。我知道您提到过您选择了 Linux 计划。但我发现在 VS Code 中该部分是隐藏的,而在 Web 上默认是 Windows。这很重要,因为只有 Linux 计划在服务器上运行 npm install

enter image description here

确保您是在服务器上构建。您可以在 VS Code 设置中找到此选项:

enter image description here

确保在发布之前设置环境变量PLAYWRIGHT_BROWSERS_PATH

enter image description here

关于javascript - 在 Azure 函数中运行 Playwright,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63949978/

相关文章:

javascript - 使用node.js fs.readStream()在electronic html5视频播放器中播放本地视频文件

javascript - 如何使用 node.js 将 _bsontype objectID 值转换为 string/objectID 以插入到 mongoDB 中

azure - Windows Azure 端点不工作

azure - 在 Azure databricks 中创建外部表

azure - 开始-AzureStorageBlobCopy 与 AzCopy : which one takes lesser time

javascript - 用vue上传文件,nodejs接收

javascript - 将大型集合保存到存储时,Redux 似乎很慢

javascript - Array.prototype.slice 奇怪的行为

node.js - SyntaxError : Unexpected end of input at Object. 解析( native )npm 请求

javascript - 使用 jwt 和 socket io 的身份验证流程