teidesu-scripts/utils/fs.ts
2025-09-14 21:52:13 +00:00

39 lines
887 B
TypeScript

import * as fsp from 'node:fs/promises'
export async function fileExists(path: string): Promise<boolean> {
try {
const stat = await fsp.stat(path)
return stat.isFile()
} catch {
return false
}
}
export async function directoryExists(path: string): Promise<boolean> {
try {
const stat = await fsp.stat(path)
return stat.isDirectory()
} catch {
return false
}
}
export function sanitizeFilename(filename: string) {
return filename.replace(/[/\\?%*:|"<>]/g, '_')
}
export async function writeWebStreamToFile(stream: ReadableStream<unknown>, path: string) {
const fd = await fsp.open(path, 'w+')
const writer = fd.createWriteStream()
for await (const chunk of stream as any) {
writer.write(chunk)
}
writer.end()
await new Promise<void>((resolve, reject) => {
writer.on('error', reject)
writer.on('finish', resolve)
})
}