SPB Git
924 B · 16 lines typescript
1import fs from "node:fs/promises";2import path from "node:path";3import { createHash } from "node:crypto";4export const DATA_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.DATA_DIR ?? "./data");5export const UPLOAD_DIR = path.join(DATA_DIR, "uploads");6export async function storeFile(buf: Buffer, originalName: string) {7  const sha256 = createHash("sha256").update(buf).digest("hex");8  const ext = (originalName.match(/\.[a-z0-9]{1,8}$/i)?.[0] ?? "").toLowerCase();9  const rel = path.join(sha256.slice(0, 2), sha256.slice(2, 4), sha256 + ext);10  const abs = path.join(UPLOAD_DIR, rel);11  await fs.mkdir(path.dirname(abs), { recursive: true });12  try { await fs.access(abs); } catch { await fs.writeFile(abs, buf); }13  return { sha256, storagePath: rel };14}15export const absPath = (rel: string) => { const p = path.join(UPLOAD_DIR, rel); if (!p.startsWith(UPLOAD_DIR)) throw new Error("bad path"); return p; };16
Files · main
Menu

Theme