Skip to content

Commit

Permalink
feat : lighthouse service added
Browse files Browse the repository at this point in the history
  • Loading branch information
soumyadip007 committed Dec 8, 2023
1 parent 4a297f0 commit 797799e
Show file tree
Hide file tree
Showing 4 changed files with 2,477 additions and 54 deletions.
119 changes: 119 additions & 0 deletions controllers/lighthouse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
const argv = require('yargs').argv;
const url = require('url');
const fs = require('fs');
const glob = require('glob');
const path = require('path');


const launchChromeAndRunLighthouse = async (url) => {
const lighthouse = (await import('lighthouse')).default;
const chromeLauncher = await import('chrome-launcher');
try {
const chrome = await chromeLauncher.launch();
const opts = {
port: chrome.port
};

const results = await lighthouse(url, opts);

await chrome.kill();

return {
js: results.lhr,
json: results.report
};
} catch (error) {
console.error('Error:', error);
throw error; // Propagate the error
}
};

const getContents = (pathStr) => {
const output = fs.readFileSync(pathStr, 'utf8', (err, results) => {
return results;
});
return JSON.parse(output);
};

const compareReports = (from, to) => {
const metricFilter = [
'first-contentful-paint',
'first-meaningful-paint',
'speed-index',
'estimated-input-latency',
'total-blocking-time',
'max-potential-fid',
'time-to-first-byte',
'first-cpu-idle',
'interactive'
]

const calcPercentageDiff = (from, to) => {
const per = ((to - from) / from) * 100;
return Math.round(per * 100) / 100;
};

for(let auditObj in from['audits']) {
if(metricFilter.includes(auditObj)) {
const percentageDiff = calcPercentageDiff(
from['audits'][auditObj].numericValue,
to['audits'][auditObj].numericValue
);

let logColor = '\x1b[37m';
const log = (() => {
if(Math.sign(percentageDiff) === 1) {
logColor = "\x1b[31m";
return `${percentageDiff.toString().replace('-','') + '%'} slower`;
}
else if(Math.sign(percentageDiff) === 0) {
return 'unchanged';
}
else {
logColor = "\x1b[32m";
return `${percentageDiff.toString().replace('-','') + '%'} faster`;
}
})();
console.log(logColor, `${from['audits'][auditObj].title} is ${log}`);
}
}
}


module.exports.launchChromeAndRunLighthouse = async () => {
// const urlObj = new URL(argv.url);
let dirName = "report";
// if(urlObj.pathname !== '/') {
// dirName = dirName + urlObj.pathname.replace(/\//g,'_');
// }

if(!fs.existsSync(dirName)) {
fs.mkdirSync(dirName);
}

const results = await launchChromeAndRunLighthouse("https://www.smashingmagazine.com/2020/09/introduction-running-lighthouse-programmatically/");

const prevReports = glob(`${dirName}/*.json`, {
sync: true
});

if(prevReports.length) {
dates = [];
for(report in prevReports) {
dates.push(new Date(path.parse(prevReports[report]).name.replace(/_/g, ':')));
}
const max = dates.reduce(function(a, b) {
return Math.max(a, b);
});
const recentReport = new Date(max).toISOString();

const recentReportContents = getContents(dirName + '/' + recentReport.replace(/:/g, '_') + '.json');

compareReports(recentReportContents, results.js);
}

fs.writeFile(`${dirName}/${results.js['fetchTime'].replace(/:/g, '_')}.json`, results.json, (err) => {
if (err) throw err;
});

}
Loading

0 comments on commit 797799e

Please sign in to comment.