Generating Lighthouse Scores using NodeJS

Lighthouse is an open-source tool which is used to generate performance of any web page. We can use CLI or chrome extension to generate lighthouse score for a web page but here is the description of how to generate lighthouse score of multiple urls present in a csv file and generate a csv file consisting of scores of Performance, Accessibility, Best-Practices and SEO for both Mobile and Desktop views.

We use the lighthouse package provided by npm and use the chrome-launcher as well to generate scores of web sites. We can download the package and use them as follows:

  • npm install --save lighthouse
  • const lighthouse = require("lighthouse")

After importing this third party package, we are ready to proceed further to import the URL file by using readFileSync method of the default fs package provided by NodeJS and store these URLs in an array from which we will iterate through all the URLs and generate scores for both Mobile and Desktop strategies.

Approach:
Follow the steps below to achieve the solution:

  1. Read the csv file using default fs npm package.
  2. Convert the data to String and split it in an array.
  3. Push the header columns in the array.
  4. Launch the chrome using chromeLauncher.launch() method.
  5. Create an options object to specify the details of output format, categories, audits and other customization if any you want to have in your output.
  6. Traverse through all the urls we have in our array and do the following for each one of it:
    • Run two loops: one for mobile and other for desktop scores by specifying options.strategy=mobile or options.strategy=desktop.
    • Call the lighthouse function with url i.e. array[i] as the first parameter and options object as the second parameter.
    • The object returned would store the details received after calling the lighthouse function.
    • We can access the scores from this object and since the scores are in decimals, we need to multiply it with 100 to get it as percentage.
    • Push the scores in the result.
  7. Append the result in a csv file and end the program.

Filename: app.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Import the required npm packages
const fs = require("fs");
const lighthouse = require("lighthouse");
const chromeLauncher = require("chrome-launcher");
  
// Read the csv file and store the
// urls in an array
var array = fs.readFileSync("URLs.csv")
                .toString().split("\n");
  
// Declare a resultant array to store 
// the generated scores and initialize
// it with headings
let result = [];
result.push(
  ", URL, Mobile_Performance, Mobile_Accessibility, 
    Mobile_Best_Practices, Mobile_SEO, 
    Desktop_Performance, Desktop_Accessibility, 
    Desktop_Best_Practices, Desktop_SEO"
);
  
// The async await is used to ensure 
// non-blocking code execution 
(async () => {
  const chrome = await chromeLauncher
    .launch({ chromeFlags: ["--headless"] })
  
  // Declaring an object to specify score 
  // for what audits, categories and type
  // of output that needs to be generated 
  const options = {
    logLevel: "info",
    output: "csv",
    onlyCategories: ["performance"
      "accessibility", "best-practices", "seo"],
    audits: [
      "first-meaningful-paint",
      "first-cpu-idle",
      "byte-efficiency/uses-optimized-images",
    ],
    port: chrome.port,
  };
  
  // Traversing through each URL 
  for (i in array) {
  
    // Separate strategy for Mobile
    // and Desktop view
    for (let x = 0; x < 2; x++) {
      let configuration = "";
  
      if (x == 0) options.strategy = "mobile";
      else options.strategy = "desktop";
  
      const runnerResult = 
        await lighthouse(array[i], options);
  
      // Current report
      const reportCsv = runnerResult.report;
  
      // URL to be put only for first iteration 
      // (mobile and not separately for desktop)
      if (x == 0) {
        result.push("\n");
        result.push(runnerResult.lhr.finalUrl);
      }
  
      // If score can't be determined, NA is 
      // put in the corresponding field.   
      if (runnerResult.lhr.categories.performance.score) {
        result.push(runnerResult.lhr
              .categories.performance.score * 100)
      } else {
        result.push("NA")
      }
  
      if (runnerResult.lhr.categories.accessibility.score) {
        result.push(runnerResult.lhr
              .categories.accessibility.score * 100)
      } else {
        result.push("NA");
      }
  
      if (runnerResult.lhr.categories["best-practices"].score) {
        result.push(runnerResult.lhr
            .categories["best-practices"].score * 100)
      } else {
        result.push("NA");
      }
  
      if (runnerResult.lhr.categories.seo.score) {
        result.push(runnerResult.lhr
              .categories.seo.score * 100)
      } else {
        result.push("NA");
      }
    }
  }
  
  // Append the result in a report.csv 
  // file and end the program
  fs.appendFileSync("lhreport.csv", result);
  await chrome.kill();
})();

chevron_right


Input:

Running the app.js file after installing the lighthouse package.

Output:

Lighthouse report file (lhreport.csv) gets generated after we run the program




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.