-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.js
More file actions
104 lines (87 loc) · 2.39 KB
/
upload.js
File metadata and controls
104 lines (87 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import {
S3Client,
PutObjectCommand,
ListObjectsV2Command,
} from "@aws-sdk/client-s3";
import { readdir, readFile, stat } from "fs/promises";
import { join, relative } from "path";
import { lookup } from "mime-types";
const R2_ACCOUNT_ID = process.env.R2_ACCOUNT_ID;
const R2_ACCESS_KEY_ID = process.env.R2_ACCESS_KEY_ID;
const R2_SECRET_ACCESS_KEY = process.env.R2_SECRET_ACCESS_KEY;
const R2_BUCKET_NAME = process.env.R2_BUCKET_NAME;
if (
!R2_ACCOUNT_ID ||
!R2_ACCESS_KEY_ID ||
!R2_SECRET_ACCESS_KEY ||
!R2_BUCKET_NAME
) {
console.error("Missing required environment variables:");
console.error(
" R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET_NAME",
);
process.exit(1);
}
const client = new S3Client({
region: "auto",
endpoint: `https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: R2_ACCESS_KEY_ID,
secretAccessKey: R2_SECRET_ACCESS_KEY,
},
});
async function getAllFiles(dir, baseDir = dir) {
const files = [];
const entries = await readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...(await getAllFiles(fullPath, baseDir)));
} else {
files.push({
path: fullPath,
key: relative(baseDir, fullPath),
});
}
}
return files;
}
async function uploadFile(filePath, key) {
const content = await readFile(filePath);
const contentType = lookup(filePath) || "application/octet-stream";
const command = new PutObjectCommand({
Bucket: R2_BUCKET_NAME,
Key: key,
Body: content,
ContentType: contentType,
});
await client.send(command);
console.log(`Uploaded: ${key} (${contentType})`);
}
async function upload() {
const publicDir = join(import.meta.dirname, "public");
try {
await stat(publicDir);
} catch {
console.error(
"public/ directory does not exist. Run the build script first.",
);
process.exit(1);
}
const files = await getAllFiles(publicDir);
if (files.length === 0) {
console.log("No files to upload.");
return;
}
console.log(
`Uploading ${files.length} files to R2 bucket: ${R2_BUCKET_NAME}`,
);
for (const file of files) {
await uploadFile(file.path, file.key);
}
console.log("Upload complete.");
}
upload().catch((err) => {
console.error("Upload failed:", err);
process.exit(1);
});