cli: create writeFile destination if necessary (#15990)
This commit is contained in:
Родитель
9a5367fcc9
Коммит
9acc3aef8c
|
@ -5,6 +5,7 @@
|
|||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
import log from 'lighthouse-logger';
|
||||
|
||||
|
@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -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';
|
||||
|
@ -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', () => {
|
||||
|
@ -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});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
Загрузка…
Ссылка в новой задаче