Search code examples
node.jslighthouse

How to add throttling in Lighthouse programmaticaly?


I'm a little bit confused how to supply throttling options via Lighthouse using NodeJS. I can do it via bash script:

lighthouse https://hazemhagrass.com --quiet --chrome-flags='--headless' --output=json --output-path=>hazem.json

Solution

  • The example below shows how to run Lighthouse programmatically as a Node module with a custom configurations.

    const lighthouse = require('lighthouse');
    const chromeLauncher = require('chrome-launcher');
    
    function launchChromeAndRunLighthouse(url, opts, config = null) {
      return chromeLauncher.launch({
        chromeFlags: opts.chromeFlags
      }).then(chrome => {
        opts.port = chrome.port;
        const options = Object.assign({}, flags, config);
        return lighthouse(url, opts).then(results => {
          // use results.lhr for the JS-consumeable output
          // https://github.com/GoogleChrome/lighthouse/blob/master/typings/lhr.d.ts
          // use results.report for the HTML/JSON/CSV output as a string
          // use results.artifacts for the trace/screenshots/other specific case you need (rarer)
          return chrome.kill().then(() => results.lhr)
        });
      });
    }
    
    const opts = {
      chromeFlags: ['--show-paint-rects']
    };
    
    // Usage:
    const config = {
      throttling: {
        rttMs: 150,
        throughputKbps: 1.6 * 1024,
        cpuSlowdownMultiplier: 4,
      }
    };
    launchChromeAndRunLighthouse('https://hazemhagrass.com', opts, config).then(results => {
      // Use results!
    });