Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
'use strict';
const fs = require('fs');
const s3 = require('gulp-s3-upload')();
const log = require('lighthouse-logger');
const gulp = require('gulp');
const config = require('config');
const DateTime = require('luxon').DateTime;
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
/**
* Run lighthouse
* @param {string} url - The url lighthouse is running against
* @param {object} flags - Flags sent into Chrome
* @param {object} config - Extra configuration
*/
function launchChromeAndRunLighthouse(url, flags, config = null) {
return chromeLauncher.launch({chromeFlags: ['--disable-gpu', '--headless', '--no-sandbox']}).then(chrome => {
flags.port = chrome.port;
console.log(flags);
return lighthouse(url, flags, config).then(results =>
chrome.kill().then(() => results)
);
});
}
/**
* Generate a report and save it to a file.
* @param {object} site - This object holds the name, url and displayName
* @param {string} type - The type of report we're generating json|html
*/
function generateReport(site, type) {
return launchChromeAndRunLighthouse(site.url, {logLevel: 'info', output: type})
.then((data) => {
data = JSON.stringify(data);
// timestamep will be used on the filename
let timeStamp = DateTime.local().toISODate();
// Directory may not exist yet
if (!fs.existsSync(`reports/${site.name}`)) {
fs.mkdirSync(`reports/${site.name}`);
}
// Directory may not exist yet
if (!fs.existsSync(`reports/${site.name}/${type}`)) {
fs.mkdirSync(`reports/${site.name}/${type}`);
}
fs.writeFileSync(`reports/${site.name}/${type}/${site.name}-${timeStamp}.${type}`, data);
})
.catch(handleError);
}
/**
* Handle error
*/
const handleError = function(e) {
console.error(e); // eslint-disable-line no-console
throw e; // Throw to exit process with status 1.
};
// const flags = {logLevel: 'info', output: 'json'}; // available options - https://github.com/GoogleChrome/lighthouse/#cli-options
log.setLevel('info');
/**
* This is the entry point to Lighthouse, this will loop through our urls and run lighthouse against them
*/
gulp.task('lighthouse', function() {
// The idea is to go through the list of sites and run lighthouse against them all
let sites = config.get('pages');
sites.forEach( async (v) => {
// First lets get JSON
// We don't want to overload the server by
// await generateReport(v, 'json');
await generateReport(v, 'html');
})
});
gulp.task('default', ['lighthouse']);
@trwatson

This comment has been minimized.

Copy link

commented Jan 10, 2018

Found this through the Lighthouse bug report. I'm curious if you'd share your finished solution for writing out the data from calling Lighthouse programmatically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.