import fs from 'node:fs'; import path from 'node:path'; import { Readable } from 'node:stream'; import { finished } from 'stream/promises'; export async function ensurePathForFile(filePath: string) { const dirPath = path.dirname(filePath); await fs.promises.mkdir(dirPath, { recursive: true }); } export async function writeFileAndCreateFolders( filePath: string, data: Readable | string | Buffer, ) { await ensurePathForFile(filePath); if (data instanceof Readable) { const write = fs.createWriteStream(filePath, { flags: 'wx', }); return finished(data.pipe(write)); } if (data instanceof Buffer) { return fs.promises.writeFile(filePath, data); } return fs.promises.writeFile(filePath, data, 'utf8'); }