如何在Node.js中以编程方式禁用Lighthouse的节流功能?
如何在Node.js环境下禁用Lighthouse的节流功能?
嘿,这个问题我熟!在Node.js里用Lighthouse时,要彻底关掉所有节流设置其实非常简单,核心就是调整Lighthouse的配置参数。我给你一步步讲清楚:
核心原理
Lighthouse的所有节流行为(包括网络延迟、带宽限制、CPU减速)都由配置中的throttling字段控制。要禁用节流,只需要把这个字段里的所有模拟参数都设为「无限制」状态就行。
两种实现方式
方式一:手动配置所有节流参数
这种方式最直观,能明确控制每一项设置,避免意外。首先确保你已经安装了必要的包:
npm install lighthouse chrome-launcher
然后编写测试代码:
const lighthouse = require('lighthouse'); const chromeLauncher = require('chrome-launcher'); async function runUnthrottledLighthouse(targetUrl) { // 启动无头Chrome实例 const chromeInstance = await chromeLauncher.launch({ chromeFlags: ['--headless=new', '--disable-gpu'] }); // 核心配置:完全禁用所有节流 const lighthouseConfig = { extends: 'lighthouse:default', settings: { throttling: { rttMs: 0, // 网络往返延迟设为0(无延迟) throughputKbps: 0, // 不限制网络吞吐量(带宽) cpuSlowdownMultiplier: 1,// CPU不减速(保持原始运行速度) requestLatencyMs: 0, // 请求延迟设为0 downloadThroughputKbps: 0,// 下载带宽无限制 uploadThroughputKbps: 0 // 上传带宽无限制 } } }; // 运行Lighthouse测试 const { lhr } = await lighthouse(targetUrl, { port: chromeInstance.port, disableStorageReset: true // 可选:保留页面存储状态,比如登录态,按需开启 }, lighthouseConfig); // 输出测试结果 console.log(`测试完成!综合得分:${lhr.score * 100}`); console.log(`各分类详情:${JSON.stringify(lhr.categories, null, 2)}`); // 关闭Chrome实例 await chromeInstance.kill(); } // 替换成你要测试的目标URL runUnthrottledLighthouse('https://example.com');
方式二:使用官方内置的「无节流」预设
Lighthouse官方提供了lighthouse:no-throttling预设,已经帮你把所有节流参数都设置为无限制状态,用起来更简洁:
const lighthouse = require('lighthouse'); const chromeLauncher = require('chrome-launcher'); async function runUnthrottledLighthouse(targetUrl) { const chromeInstance = await chromeLauncher.launch({chromeFlags: ['--headless=new']}); // 直接调用无节流预设 const lighthouseConfig = { extends: 'lighthouse:no-throttling' }; const { lhr } = await lighthouse(targetUrl, {port: chromeInstance.port}, lighthouseConfig); console.log(`综合得分:${lhr.score * 100}`); await chromeInstance.kill(); } runUnthrottledLighthouse('https://example.com');
注意事项
- 确保你的Lighthouse版本在v6.0以上,旧版本的配置项可能略有差异,建议使用最新稳定版
- 如果测试需要保留Chrome的某些状态(比如登录会话),可以加上
disableStorageReset: true配置 - 两种方式的最终效果完全一致,选哪种取决于你是否需要在无节流基础上调整其他自定义配置
内容的提问来源于stack exchange,提问作者RedDragon
相关产品推荐
相关产品推荐

