chrome aws lambda+灯塔总是导致错误:connect ECONNREFUSED 127.0.0.1:92



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

测试处理程序(在另一个终端中)

curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"payload":"hello world!"}'

预期结果:

Lighthouse运行,我可以读取报告属性。

实际结果:

当灯塔真正运行时,无论我尝试什么设置,我都会得到这个:

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)"]

我设法从Lighthouse得到了结果。感谢您的示例

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)

我希望有人能指出我做错了什么,或者可能错过了配置

最新更新