fix: log files were not re-created if their folder was removed at run-time

Massimo Melina committed May 2, 2023 at 12:16 UTC aedd66108d8742bcf0d767b2c3797613662b1b7d
2 files changed +14 -4
src/log.ts
+3 -3
@@ -8,7 +8,7 @@ import * as util from 'util'
8 import { stat } from 'fs/promises'
9 import { DAY } from './const'
10 import _ from 'lodash'
11 -import { prepareFolder } from './util-files'
11 +import { createFileWithPath, prepareFolder } from './util-files'
12 import { getCurrentUsername } from './perm'
13 import { makeNetMatcher, tryJson } from './misc'
14
@@ -38,8 +38,8 @@ class Logger {
38 }
39
40 reopen() {
41 - return this.stream = createWriteStream(this.path, { flags: 'a' })
42 - .on('error', () => this.stream = undefined)
41 + return this.stream = createFileWithPath(this.path, { flags: 'a' })
42 + ?.on('error', () => this.stream = undefined)
43 }
44 }
45
src/util-files.ts
+11 -1
@@ -2,7 +2,7 @@
2
3 import fs from 'fs/promises'
4 import { wait } from './misc'
5 -import { createWriteStream, watch } from 'fs'
5 +import { createWriteStream, mkdirSync, watch } from 'fs'
6 import { basename, dirname } from 'path'
7 import glob from 'fast-glob'
8 import { IS_WINDOWS } from './const'
@@ -138,6 +138,16 @@ export async function prepareFolder(path: string, dirnameIt=true) {
138 }
139 }
140
141 +export function createFileWithPath(path: string, options?: Parameters<typeof createWriteStream>[1]) {
142 + const folder = dirname(path)
143 + if (!isWindowsDrive(folder))
144 + try { mkdirSync(folder, { recursive: true }) }
145 + catch {
146 + return
147 + }
148 + return createWriteStream(path, options)
149 +}
150 +
151 export function isValidFileName(name: string) {
152 return !/^\.\.?$|[/:*?"<>|\\]/.test(name)
153 }
\ No newline at end of file