From 92c9481f7ce1eb97136b67f7376892f2836f5da4 Mon Sep 17 00:00:00 2001 From: Cody Kaup Date: Fri, 1 Nov 2024 16:01:28 -0500 Subject: [PATCH] Ensure parent directory exists before writing log/diagnostics file --- node-src/lib/log.ts | 12 ++++++++---- node-src/lib/writeChromaticDiagnostics.ts | 9 ++++++--- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/node-src/lib/log.ts b/node-src/lib/log.ts index ffa999cab..4773e79af 100644 --- a/node-src/lib/log.ts +++ b/node-src/lib/log.ts @@ -1,6 +1,7 @@ import chalk from 'chalk'; import debug from 'debug'; -import { createWriteStream, rm } from 'fs'; +import { createWriteStream, mkdirSync, rm } from 'fs'; +import path from 'path'; import stripAnsi from 'strip-ansi'; import { format } from 'util'; @@ -96,13 +97,16 @@ const fileLogger = { this.append = () => {}; this.queue = []; }, - initialize(path: string, onError: LogFunction) { - rm(path, { force: true }, (err) => { + initialize(filepath: string, onError: LogFunction) { + rm(filepath, { force: true }, (err) => { if (err) { this.disable(); onError(err); } else { - const stream = createWriteStream(path, { flags: 'a' }); + // Ensure the parent directory exists before we create the stream + mkdirSync(path.dirname(filepath), { recursive: true }); + + const stream = createWriteStream(filepath, { flags: 'a' }); this.append = (...messages: string[]) => { stream?.write( messages diff --git a/node-src/lib/writeChromaticDiagnostics.ts b/node-src/lib/writeChromaticDiagnostics.ts index 8fcd3a8d6..b8e27117e 100644 --- a/node-src/lib/writeChromaticDiagnostics.ts +++ b/node-src/lib/writeChromaticDiagnostics.ts @@ -1,11 +1,11 @@ -import jsonfile from 'jsonfile'; +import { mkdirSync } from 'fs'; +import { writeFile } from 'jsonfile'; +import path from 'path'; import { Context } from '..'; import wroteReport from '../ui/messages/info/wroteReport'; import { redact } from './utils'; -const { writeFile } = jsonfile; - /** * Extract important information from ctx, sort it and output into a json file * @@ -17,6 +17,9 @@ export async function writeChromaticDiagnostics(ctx: Context) { } try { + // Ensure the parent directory exists before writing file + mkdirSync(path.dirname(ctx.options.diagnosticsFile), { recursive: true }); + await writeFile(ctx.options.diagnosticsFile, getDiagnostics(ctx), { spaces: 2 }); ctx.log.info(wroteReport(ctx.options.diagnosticsFile, 'Chromatic diagnostics')); } catch (error) {