Skip to content

Commit

Permalink
cli: create writeFile destination if necessary (#15990)
Browse files Browse the repository at this point in the history
  • Loading branch information
servusdei2018 authored Nov 14, 2024
1 parent 9a5367f commit 9acc3ae
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
15 changes: 10 additions & 5 deletions cli/printer.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import fs from 'fs';
import path from 'path';

import log from 'lighthouse-logger';

Expand Down Expand Up @@ -58,13 +59,17 @@ function writeToStdout(output) {
*/
function writeFile(filePath, output, outputMode) {
return new Promise((resolve, reject) => {
// TODO: make this mkdir to the filePath.
fs.writeFile(filePath, output, (err) => {
if (err) {
fs.mkdir(path.dirname(filePath), {recursive: true}, (err) => {
if (err && err.code !== 'EEXIST') {
return reject(err);
}
log.log('Printer', `${OutputMode[outputMode]} output written to ${filePath}`);
resolve();
fs.writeFile(filePath, output, (err) => {
if (err) {
return reject(err);
}
log.log('Printer', `${OutputMode[outputMode]} output written to ${filePath}`);
resolve();
});
});
});
}
Expand Down
23 changes: 19 additions & 4 deletions cli/test/cli/printer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import assert from 'assert/strict';
import fs from 'fs';
import path from 'path';

import {readJson} from '../../../core/test/test-utils.js';
import * as Printer from '../../printer.js';
Expand Down Expand Up @@ -34,11 +35,9 @@ describe('Printer', () => {
});

it('throws for invalid paths', () => {
const path = '!/#@.json';
const path = '//#@.json';
const report = JSON.stringify(sampleResults);
return Printer.write(report, 'html', path).catch(err => {
assert.ok(err.code === 'ENOENT');
});
return assert.rejects(Printer.write(report, 'html', path));
});

it('returns output modes', () => {
Expand All @@ -49,4 +48,20 @@ describe('Printer', () => {
assert.strictEqual(typeof mode, 'string');
});
});

it('creates missing directories when writing to file', () => {
const dirPath = './non/existent/directory/.test-file.json';
const report = JSON.stringify(sampleResults);
const dir = path.dirname(dirPath);
if (fs.existsSync(dir)) {
fs.rmdirSync(dir, {recursive: true});
}
return Printer.write(report, 'json', dirPath).then(_ => {
assert.ok(fs.existsSync(dir), `Directory ${dir} should exist now`);
const fileContents = fs.readFileSync(dirPath, 'utf8');
assert.ok(/lighthouseVersion/gim.test(fileContents));
fs.unlinkSync(dirPath);
fs.rmdirSync(dir, {recursive: true});
});
});
});

0 comments on commit 9acc3ae

Please sign in to comment.