Skip to content

Commit 9acc3ae

Browse files
cli: create writeFile destination if necessary (#15990)
1 parent 9a5367f commit 9acc3ae

File tree

2 files changed

+29
-9
lines changed

2 files changed

+29
-9
lines changed

cli/printer.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
*/
66

77
import fs from 'fs';
8+
import path from 'path';
89

910
import log from 'lighthouse-logger';
1011

@@ -58,13 +59,17 @@ function writeToStdout(output) {
5859
*/
5960
function writeFile(filePath, output, outputMode) {
6061
return new Promise((resolve, reject) => {
61-
// TODO: make this mkdir to the filePath.
62-
fs.writeFile(filePath, output, (err) => {
63-
if (err) {
62+
fs.mkdir(path.dirname(filePath), {recursive: true}, (err) => {
63+
if (err && err.code !== 'EEXIST') {
6464
return reject(err);
6565
}
66-
log.log('Printer', `${OutputMode[outputMode]} output written to ${filePath}`);
67-
resolve();
66+
fs.writeFile(filePath, output, (err) => {
67+
if (err) {
68+
return reject(err);
69+
}
70+
log.log('Printer', `${OutputMode[outputMode]} output written to ${filePath}`);
71+
resolve();
72+
});
6873
});
6974
});
7075
}

cli/test/cli/printer-test.js

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import assert from 'assert/strict';
88
import fs from 'fs';
9+
import path from 'path';
910

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

3637
it('throws for invalid paths', () => {
37-
const path = '!/#@.json';
38+
const path = '//#@.json';
3839
const report = JSON.stringify(sampleResults);
39-
return Printer.write(report, 'html', path).catch(err => {
40-
assert.ok(err.code === 'ENOENT');
41-
});
40+
return assert.rejects(Printer.write(report, 'html', path));
4241
});
4342

4443
it('returns output modes', () => {
@@ -49,4 +48,20 @@ describe('Printer', () => {
4948
assert.strictEqual(typeof mode, 'string');
5049
});
5150
});
51+
52+
it('creates missing directories when writing to file', () => {
53+
const dirPath = './non/existent/directory/.test-file.json';
54+
const report = JSON.stringify(sampleResults);
55+
const dir = path.dirname(dirPath);
56+
if (fs.existsSync(dir)) {
57+
fs.rmdirSync(dir, {recursive: true});
58+
}
59+
return Printer.write(report, 'json', dirPath).then(_ => {
60+
assert.ok(fs.existsSync(dir), `Directory ${dir} should exist now`);
61+
const fileContents = fs.readFileSync(dirPath, 'utf8');
62+
assert.ok(/lighthouseVersion/gim.test(fileContents));
63+
fs.unlinkSync(dirPath);
64+
fs.rmdirSync(dir, {recursive: true});
65+
});
66+
});
5267
});

0 commit comments

Comments
 (0)