search
HomeWeb Front-endJS TutorialHow to use NodeJS + Lighthouse + Gulp to build an automated website performance testing tool

This article mainly introduces how to use NodeJS Lighthouse Gulp to build automated website performance testing tools. It has a certain reference value. Now I share it with you. Friends in need can refer to it.

Assuming you still I don’t know what Lighthouse is

Lighthouse is an open source tool owned by Google that can automatically detect website quality. It has a friendly interface, simple operation, diverse usage methods, and comprehensive perspectives. You can use it to test any web page. Normally Users, QA, and developers can all get started quickly.

Startup posture

Difficulty level 1

There are many ways to use Lighthouse. The simplest one is to use Chrome's developer tools. The steps are as follows:

  1. Open Chrome browser

  2. Press F12

  3. Open the audits tab in the pop-up window

  4. Click Perform an audit...check all

  5. Run audit

##Difficulty level 2

You can also use the command line.

  1. Install Node

  2. Install Lighthouse

    npm install -g lighthouse

  3. run in the command line

    lighthouse

The above two usage methods are not the focus of this article. If you want to learn more, you can refer to Run Lighthouse in DevTools

Difficulty level 3

Since I am learning NodeJS recently, I decided to use Node 8 Gulp to run lighthouse. In order to improve the accuracy of the results, I ran lighthouse 10 times for each task, and We only care about the

first-meaningful-paint milliseconds in the result indicator, and finally take the average of 10 times. For the sake of visualization and readability, the final results are displayed in the form of a web page, and users can view it on the web page. You can also see the average number of milliseconds to first-meaningful-paint after each execution of Lighthouse. If the user is interested in the details of a certain execution, he can click on the link to view it. The final result looks like this:

How to use NodeJS + Lighthouse + Gulp to build an automated website performance testing tool

How to use NodeJS + Lighthouse + Gulp to build an automated website performance testing tool

Environment setup

Install Node 8

Install dependencies Package

npm i lighthouse --save-dev
npm i chrome-launcher --save-dev
npm i fs-extra --save-dev
npm i gulp --save-dev
Configuration

Create the Lighthouse configuration file

lighthouse-config.js in the project root directory. Here we all use the default configuration. To use the default configuration, you need to configure The file declares extends: 'lighthouse:default'.

module.exports = {
    extends: 'lighthouse:default'
}
If readers need to know more detailed configuration options, please refer to:

  1. Lighthouse Most of this article is about the command line, and command line parameters can also be used Node

  2. throttlingThis article is about network simulation

  3. Default Config Specific default configuration parameters

  4. Web Page Test simulates different network speeds

  5. Emulation simulates different devices

Coding

In the project root directory Create

gulpfile.js, first introduce all dependent tools:

const gulp = require('gulp');
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const printer = require('lighthouse/lighthouse-cli/printer');
const Reporter = require('lighthouse/lighthouse-core/report/report-generator');
const fs = require('fs-extra');
const config = require('.lighthouse-config.js');
Before starting to use lighthouse, first create a method to write files, which will be used to finally generate a customized report file :

async function write(file, report) {
    try {
        await fs.outputFile(file, report);
    } catch (Error e) {
        console.log("error while writing report ", e);
    }
}
Before calling Lighthouse, we need to first start a Chrome instance and provide the port number to Lighthouse.

--headless means not opening the browser window.

async function launchChrome() {
    let chrome;
    try {
        chrome =  await chromeLauncher.launch({
          chromeFlags: [
            "--disable-gpu",
            "--no-sandbox",
            "--headless"
          ],
          enableExtensions: true,
          logLevel: "error"
        });
        console.log(chrome.port)
        return {
            port: chrome.port,
            chromeFlags: [
                "--headless"
            ],
            logLevel: "error"
         }
    } catch (e) {
        console.log("Error while launching Chrome ", e);
    }
}
After the Chrome instance is started, we can call Lighthouse. When calling, we must provide the website that needs to be performance tested, parameters, and the configuration created previously. The parameters include Chrome startup port, startup method (whether headless and other information).

async function lighthouseRunner(opt) {
    try {
        return await lighthouse("https://www.baidu.com", opt, config);
    } catch (e) {
        console.log("Error while running lighthouse");
    }
}
The return result of Lighthouse is a json object containing performance test results, final version of configuration parameters, indicator grouping and other information. Readers can refer to Understanding Results for a deeper understanding.

Since we need to use the official Lighthouse template to generate the report, we call the official method. Note that the first parameter is passed in
result.lhr, and the second parameter is declared to generate an html report (you can also Generate reports in csv and other formats).

function genReport(result) {
    return Reporter.generateReport(result.lhr, 'html');
}
Next we write a function that strings together the above methods. First, start a Chrome instance, then pass some parameters of the Chrome instance to Lighthouse, use the results run by lighthouse to generate a report, and write Enter the html file. The html file should have a timestamp and execution sequence as a unique identifier. The

start method returns first-meaningful-paint in the result (this is the indicator we are most concerned about. Readers can replace it according to their own needs. For specific indicators, please refer to Lighthouse).

async function run(timestamp, num) {
    let chromeOpt = await launchChrome();
    let result = await lighthouseRunner(chromeOpt);
    let report = genReport(result);
    await printer.write(report, 'html', `./cases/lighthouse-report@${timestamp}-${num}.html`);
    return result.lhr.audits['first-meaningful-paint'].rawValue;
    await chrome.kill();
}

下面, 我们可以正式开始写一个 gulp task 啦,首先获得当前时间戳,用于最终生成的报告命名,然后声明一个数组,用于记录每次跑 Lighthouse 生成的 first-meaningful-paint 毫秒数,然后跑10次 Lighthouse, 使用提前创建的模板文件,根据这10的结果,生成一个汇总报告,这里,笔者使用了Lighthouse对外暴露的工具函数进行字符串的替换。

gulp.task('start', async function() {
  let timestamp = Date.now();
  let spent = [];
  for(let i=0; i<p>最后的最后, 执行:</p><pre class="brush:php;toolbar:false">gulp start

万事大吉。
附上汇总界面的模板源码:

nbsp;html>


  <meta>
  <meta>
  <title>Lighthouse Summary Report</title>
  <style>
    body {
      font-family: sans-serif;
    }
    table {
      margin: auto;
    }
    tr {
      border: 1px solid grey;
    }
    h1 {
       text-align: center;
       margin: 30px auto 50px auto
    }
  </style>


  

Performance Summary Report

                          
      Case No.            First Meaningful Paint            Link To Details     
<script> let timespent = %%TIME_SPENT%%; let timestamp = %%TIMESTAMP%%; let tableBody = document.getElementById("tableBody"); let content = &#39;&#39;; for(let i=0; i < timespent.length; i++) { content += `<tr style="border: 1px solid grey"> <td> ${i+1} <td> ${timespent[i]} <td> <a href="../../cases/lighthouse-report@${timestamp}-${i}.html">View Details ` } let total = timespent.reduce((i, j) => { return i + j; }) let count = timespent.filter(function(i) { return i}).length content += `<tr> <td> AVG <td> ${total / count} ` tableBody.innerHTML = content; </script>

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

 jQuery+AJAX+PHP+MySQL开发搜索无跳转无刷新的功能

关于vue中extend,mixins,extends,components,install的操作

Vue+Mock.js如何搭建前端独立开发环境

The above is the detailed content of How to use NodeJS + Lighthouse + Gulp to build an automated website performance testing tool. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool