From 9acc3aef8c48fbafd9c677690ca6ef411448a0a0 Mon Sep 17 00:00:00 2001 From: Nate <37554478+servusdei2018@users.noreply.github.com> Date: Wed, 13 Nov 2024 21:11:00 -0500 Subject: [PATCH] cli: create writeFile destination if necessary (#15990) --- cli/printer.js | 15 ++++++++++----- cli/test/cli/printer-test.js | 23 +++++++++++++++++++---- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/cli/printer.js b/cli/printer.js index 2105fa3be7b3..0f0d09df28cd 100644 --- a/cli/printer.js +++ b/cli/printer.js @@ -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(); + }); }); }); } diff --git a/cli/test/cli/printer-test.js b/cli/test/cli/printer-test.js index 82f5cc1c37c7..14a9213af399 100644 --- a/cli/test/cli/printer-test.js +++ b/cli/test/cli/printer-test.js @@ -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}); + }); + }); });