-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
95 lines (81 loc) · 2.37 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import lighthouse from 'lighthouse';
import { launch } from 'chrome-launcher';
import fs from 'fs';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import fetch from 'node-fetch';
import { mkdirp } from 'mkdirp';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { version } = require('./package.json');
if (!globalThis.fetch) {
globalThis.fetch = fetch;
}
const argv = yargs(hideBin(process.argv))
.usage('Usage: $0 -u [url]')
.option('url', {
alias: 'u',
describe: 'URL to analyze with Lighthouse',
type: 'string',
demandOption: 'URL is required',
nargs: 1,
})
.option('categories', {
alias: 'c',
describe: 'Categories to analyze (comma-separated, no spaces)',
type: 'string',
default: 'performance,accessibility,best-practices,seo',
})
.option('format', {
alias: 'f',
describe: 'Report format',
choices: ['html', 'json'],
default: 'html',
})
.version(version)
.alias('v', 'version')
.help('h')
.alias('h', 'help').argv;
/**
*
* @param {string} message
* @param {string} level
*/
function log(message, level = 'info') {
console[level](message);
}
/**
*
* @param {string} url
* @param {string} categories
* @param {'html' | 'json'} format
*/
async function run(url, categories, format) {
const dir = `results/${new Date().toISOString()}`;
await mkdirp(dir);
const chrome = await launch({ chromeFlags: ['--headless'] });
const options = {
logLevel: 'info',
output: format,
onlyCategories: categories.split(','),
port: chrome.port,
};
try {
const result = await lighthouse(url, options);
const file = `${dir}/report.${format}`;
fs.writeFileSync(file, result.report);
log(`Report is done for ${result.lhr.finalUrl}`);
if (categories.split(',').includes('performance')) {
log(`Performance score was ${result.lhr.categories.performance.score * 100}`);
}
log(`Report saved as ${dir}`);
} catch (error) {
log('Error running Analyzer: ' + error, 'error');
} finally {
await chrome.kill();
}
}
run(argv.url, argv.categories, argv.format).catch((error) => {
log('Failed to run Analyzer: ' + error, 'error');
process.exit(1);
});