Skip to content

Commit

Permalink
Add option to export to file (GoogleChromeLabs#128)
Browse files Browse the repository at this point in the history
  • Loading branch information
rodriigomedeiros committed Aug 23, 2021
1 parent 57a0ea6 commit 5eb09fa
Show file tree
Hide file tree
Showing 7 changed files with 89 additions and 6 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ node_modules
yarn.lock
.nyc_output/
coverage/
.history/
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,27 @@ Values: `mobile` `desktop`

Strategy to use when analyzing the page.

##### format

Type: `string`<br>
Default: `cli`<br>
Values: `cli` `tap` `json`

Report output format.

##### toFile

Type: `boolean`<br>
Default: `false`

Defines whether the report output will be in files. Only works if combined with Json format.

##### filePath

Type: `string`<br>

Path to generated file. Only works if combined with toFile option.

##### locale

Type: `string`<br>
Expand Down
2 changes: 2 additions & 0 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const cli = meow(`
--key Google API Key. By default the free tier is used
--strategy Strategy to use when analyzing the page: mobile|desktop
--format Output format: cli|json|tap
--toFile Output report in files. Only works if combined with Json format
--filePath Path to generated file. Only works if combined with toFile option
--locale Locale results should be generated in
--threshold Threshold score to pass the PageSpeed test
--links Adds link with more info about opportunities
Expand Down
1 change: 1 addition & 0 deletions lib/options-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const getOptions = (url, options) => {
options = Object.assign({strategy: 'mobile'}, options);
options.nokey = options.key === undefined;
options.url = prependHttp(url);
options.toFile = options.toFile !== undefined && options.toFile !== false;
return options;
};

Expand Down
44 changes: 40 additions & 4 deletions lib/output.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const prettyMs = require('pretty-ms');
const terminalLink = require('terminal-link');
const {getThreshold, getReporter} = require('./../lib/options-handler');
const {getLink} = require('./../lib/string-utils');
const fs = require('fs');

function overview(url, strategy, scores) {
return [
Expand Down Expand Up @@ -89,20 +90,55 @@ const opportunities = (lighthouseResult, links) => {
};

const convertToPercentum = num => Math.round(num * 100);
const isInTest = typeof global.it === 'function';

module.exports = (parameters, response) => {
return Promise.resolve().then(() => {
const renderer = require(`./formats/${getReporter(parameters.format)}`);
const {format, strategy, filePath} = parameters;

const renderer = require(`./formats/${getReporter(format)}`);
const threshold = getThreshold(parameters.threshold);
const {lighthouseResult, loadingExperience = {}, id} = response;
const humanizedUrl = humanizeUrl(id);

console.log(renderer(
overview(humanizeUrl(id), parameters.strategy, lighthouseResult),
const render = renderer(
overview(humanizedUrl, strategy, lighthouseResult),
fieldData(loadingExperience.metrics),
labData(lighthouseResult),
opportunities(lighthouseResult, parameters.links),
threshold
));
);

console.log(render);

if (parameters.toFile && format === 'json' && !isInTest) {
const urlFilename = humanizedUrl.replaceAll('.', '-').replaceAll('/', '--');

const dateFilename = new Date()
.toISOString()
.slice(0, 19)
.replace(/\D/g, '');

const jsonFileName = `${filePath ? filePath + '/' : ''}${urlFilename}_${strategy}_${dateFilename}`;

const responseJsonStringfy = JSON.stringify(response);

fs.writeFileSync(`${jsonFileName}_short.json`, render, err => {
if (err) {
return console.error(err);
}
});

fs.writeFileSync(
`${jsonFileName}_full.json`,
responseJsonStringfy,
err => {
if (err) {
return console.error(err);
}
}
);
}

const score = convertToPercentum(lighthouseResult.categories.performance.score);
if (score < threshold) {
Expand Down
2 changes: 1 addition & 1 deletion test/format.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const {assert} = require('chai');
const stripAnsi = require('strip-ansi');
const output = require('../lib/output');
const response = require('./fixtures/response');
const response = require('./fixtures/response.json');

describe('Formatting', () => {
beforeEach(function () {
Expand Down
24 changes: 23 additions & 1 deletion test/options-handler.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ describe('Options handler method', () => {
describe('getOptions method', () => {
const defaultConfig = {
nokey: true,
url: 'http://addyosmani.com'
url: 'http://addyosmani.com',
strategy: 'mobile',
toFile: false
};
it('should return strategy "mobile" if no strategy is passed', () => {
const expectedOutput = {
Expand All @@ -23,6 +25,26 @@ describe('Options handler method', () => {
};
expect(getOptions('http://addyosmani.com', {strategy: 'desktop'})).to.eql(expectedOutput);
});
it('should return toFile "false" if is not specificied', () => {
const expectedOutput = {
...defaultConfig
};
expect(getOptions('http://addyosmani.com')).to.eql(expectedOutput);
});
it('should return toFile "true" if is specificied', () => {
const expectedOutput = {
...defaultConfig,
toFile: true
};
expect(getOptions('http://addyosmani.com', {toFile: true})).to.eql(expectedOutput);
});
it('should return "~/" as path to file', () => {
const expectedOutput = {
...defaultConfig,
filePath: '~/'
};
expect(getOptions('http://addyosmani.com', {filePath: '~/'})).to.eql(expectedOutput);
});
});

describe('getThreshold method', () => {
Expand Down

0 comments on commit 5eb09fa

Please sign in to comment.