coderank-server-data/utils/s3-download.ts
2026-01-26 15:53:24 +01:00

39 lines
944 B
TypeScript

import { S3Client } from "bun";
import { createWriteStream } from "fs";
import path from "path";
type Params = {
downloadPath: string;
downloadFileName: string;
folder?: string;
};
const client = new S3Client({
accessKeyId: process.env.CLOUDFLARE_R2_ACCESS_KEY_ID,
secretAccessKey: process.env.CLOUDFLARE_R2_SECRET,
bucket: "coderank",
endpoint: process.env.CLOUDFLARE_R2_ENDPOINT,
});
export default async function s3DownloadFile({
downloadPath,
folder,
downloadFileName,
}: Params) {
let finalFileName = path.join(folder || "", downloadFileName);
const s3file = client.file(finalFileName);
const writable = createWriteStream(downloadPath);
const reader = s3file.stream().getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
writable.write(value);
}
writable.end();
console.log("Download complete!");
}