Fix: create parent dir before write

This commit is contained in:
SukkaW
2024-07-23 17:58:45 +08:00
parent 553dd62eb1
commit fc3ae52baa
6 changed files with 38 additions and 13 deletions

View File

@@ -1,3 +1,7 @@
import { dirname } from 'path';
import fs from 'fs';
import fsp from 'fs/promises';
interface Peek {
<T = undefined>(promise: T | Promise<T>): Promise<T> | T,
status<T = undefined>(
@@ -11,3 +15,21 @@ noopPeek.status = () => 'unknown';
export const peek: Peek = typeof Bun !== 'undefined'
? Bun.peek
: noopPeek as Peek;
interface Write {
(
destination: string,
input: NodeJS.TypedArray | string,
): Promise<unknown>
}
export const writeFile: Write = typeof Bun !== 'undefined'
? Bun.write
: (async (destination: string, input) => {
const dir = dirname(destination);
if (!fs.existsSync(dir)) {
await fsp.mkdir(dir, { recursive: true });
}
return fsp.writeFile(destination, input, { encoding: 'utf-8' });
});

View File

@@ -8,6 +8,7 @@ import fsp from 'fs/promises';
import { sort } from './timsort';
import { fastStringArrayJoin } from './misc';
import { readFileByLine } from './fetch-text-by-line';
import { writeFile } from './bun';
export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
let isEqual = true;
@@ -70,7 +71,7 @@ export async function compareAndWriteFile(span: Span, linesA: string[], filePath
await span.traceChildAsync(`writing ${filePath}`, async () => {
// if (linesALen < 10000) {
return fsp.writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
// }
// const writer = file.writer();