Node.js 铬合金aws lambda+;灯塔总是导致错误:connect ECONREFUSSED 127.0.0.1:9222

Node.js 铬合金aws lambda+;灯塔总是导致错误:connect ECONREFUSSED 127.0.0.1:9222,node.js,aws-lambda,lighthouse,aws-lambda-puppeteer,chrome-aws-lambda,Node.js,Aws Lambda,Lighthouse,Aws Lambda Puppeteer,Chrome Aws Lambda,Dockerfile FROM public.ecr.aws/lambda/nodejs:12 COPY index.js package.json /var/task/ RUN npm install --save-prod CMD [ "index.handler" ] package.json { "name": "lighthouse2", "version": "1.0.0

Dockerfile

FROM public.ecr.aws/lambda/nodejs:12

COPY index.js package.json /var/task/

RUN npm install --save-prod

CMD [ "index.handler" ]
package.json

{
    "name": "lighthouse2",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "chrome-aws-lambda": "^7.0.0",
        "puppeteer-core": "^7.0.4",
        "lighthouse": "^7.1.0"
    }
}
index.js

const chromium = require('chrome-aws-lambda');
const lighthouse = require('lighthouse');

exports.handler = async(event, context, callback) => {
    let result = null;
    let chrome = null;

    try {
        console.log('Launching puppeteer chromium');
        let chromiumOptions = {
            args: chromium.args,
            defaultViewport: chromium.defaultViewport,
            executablePath: await chromium.executablePath,
            headless: chromium.headless,
            ignoreHTTPSErrors: true
        };
        const command = await chromium.puppeteer.launch(chromiumOptions)
            .then((chrome) => {
                console.log('launch.then called');
                return {
                    chrome,
                    async start() {
                        console.log('function start called');

                        const options = {logLevel: 'info', onlyCategories: ['performance']};
                        const runnerResult = await lighthouse('https://www.example.com', options)

                        console.log('Report is done for', runnerResult.lhr.finalUrl);
                        console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100);

                        await chrome.kill();
                    }
                }
            })
            .catch(err => console.error(err));

        console.log('Launched.');

        return await command.start();
    } catch (error) {
        console.log(error);
        return callback(error);
    } finally {
        if (chrome !== null) {
            await chrome.close();
        }
    }

    return callback(null, result);
};
构建测试Docker映像:

docker build -t lighthouse2 .; docker run --rm -p 9000:8080 lighthouse2
测试处理程序(在另一个终端中)

预期结果:

docker build -t lighthouse2 .; docker run --rm -p 9000:8080 lighthouse2
灯塔在运行,我可以阅读报告属性

实际结果:

docker build -t lighthouse2 .; docker run --rm -p 9000:8080 lighthouse2
当灯塔实际运行时,无论我尝试什么设置,我都会得到以下信息:

Wed, 17 Feb 2021 23:24:18 GMT status Connecting to browser
Wed, 17 Feb 2021 23:24:18 GMT CriConnection:warn Cannot create new tab; reusing open tab.
Wed, 17 Feb 2021 23:24:18 GMT status Disconnecting from browser...
Wed, 17 Feb 2021 23:24:18 GMT CriConnection:error sendRawMessage() was called without an established connection.
Wed, 17 Feb 2021 23:24:18 GMT GatherRunner disconnect:error sendRawMessage() was called without an established connection.
} port: 9222127.0.0.1',,terConnect [as oncomplete] (net.js:1144:16) {   INFO    Error: connect ECONNREFUSED 127.0.0.1:9222
2021-02-17T23:24:18.145Z        8cd07390-6550-40b7-87a5-c162fc55eedf    ERROR   Invoke Error    {"errorType":"Error","errorMessage":"connect ECONNREFUSED 127.0.0.1:9222","code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","address":"127.0.0.1","port":9
222,"stack":["Error: connect ECONNREFUSED 127.0.0.1:9222","    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)"]

我设法从灯塔那里得到了结果。多亏了你的例子

const lighthouse = require('lighthouse');
const chromium = require('chrome-aws-lambda');
const log = require('lighthouse-logger');

exports.lambdaHandler = async (event) => {
  let browser;
  let response;
  log.setLevel("error");

  try {
    browser = await chromium.puppeteer.launch({
      args: [...chromium.args, "--remote-debugging-port=9222"],
      defaultViewport: chromium.defaultViewport,
      executablePath: await chromium.executablePath,
      headless: chromium.headless,
      ignoreHTTPSErrors: true,
    });

    const options = {
      output: "json",
      preset: 'mobile',
      onlyCategories: ["performance", "seo", "accessibility", "best-practices"],
      port: 9222,
    }

    const url = 'https://www.google.com';

    const result = await lighthouse(url, options);
    console.log(`Audited ${url} in ${result.lhr.timing.total} ms.`);

    const report = JSON.parse(result.report);
      
    response = {
      statusCode: 200,
      body: {
        'Perfomance': report['categories']['performance']['score'],
        'Accessibility': report['categories']['accessibility']['score'],
        'SEO': report['categories']['seo']['score'],
        'BestPractices': report['categories']['best-practices']['score'],
        'ErrorMessage': report['audits']['speed-index']['errorMessage']
      }
    }

  } catch (error) {
    console.error(error);

    response = {
      statusCode: 500,
      body: error
    }
  } finally {
    if (browser !== null) {
      await browser.close();
    }
  }

  return response;
};
然而,我对成绩有意见。大多数情况下,性能分数返回null。错误信息显示:

Chrome didn't collect any screenshots during the page load. 
Please make sure there is content visible on the page, and 
then try re-running Lighthouse. (NO_SCREENSHOTS)

我希望有人能指出我做错了什么,或者可能遗漏了一个配置

在chrome标志中添加“-remote debugation port=9222”,在lighthouse标志中添加port:9222确实解决了我的问题。(现在我得到了你的空性能分数问题。)我发现如果你将输出设置为HTML,这是可行的。lighthouse运行的输出无论如何都将包含这两者,因此您可以稍后获取JSON数据。