Solvedlighthouse Is there a way to generate html report using lighthouse programmatically.

Sorry if I missed this anywhere but I am trying to find how to generate the html using lighthouse using the example given in docs. https://github.com/GoogleChrome/lighthouse/blob/HEAD/docs/readme.md#using-programmatically

I could generate the html by calling lighthouse-cli directly but could not do it using above script. My opts are:

const opts = {
  chromeFlags: ['--show-paint-rects'],
  output: 'html',
  'output-path': './lighthouse-results.html',
  'save-assets': true
};
16 Answers

✔️Accepted Answer

@patrickhulce thank you for that!

I'm still confused and I did it work in a hacky way. All I want is to save the HTML reports in a specific location. This is my solution but I would love feedback if there is a better way to do this.

Thank you!!

```javascript
const fs = require('fs');
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const log = require('lighthouse-logger');

(async () => {
  log.setLevel('info');
  const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
  const options = {output: 'html', onlyCategories: ['performance'], port: chrome.port};
  const runnerResult = await lighthouse('https://example.com', options);

  // `.report` is the HTML report as a string
  const reportHtml = runnerResult.report;
  fs.writeFileSync('lhreport.html', reportHtml);

  // `.lhr` is the Lighthouse Result as a JS object
  console.log('Report is done for', runnerResult.lhr.finalUrl);
  console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100);

  await chrome.kill();
})();

Other Answers:

I did it like this:

const lighthouse = require('lighthouse');
const ReportGenerator = require('lighthouse/lighthouse-core/report/report-generator');

const report = await lighthouse(page.url(), { port: port }, config).then(results => {
  return results;
});
const html = ReportGenerator.generateReport(report.lhr, 'html')

MIght be worth it to update the docs for this.

More Issues: