/
image-upload.mjs
91 lines (78 loc) · 2.2 KB
/
image-upload.mjs
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
import fetch, { FormData, fileFromSync } from "node-fetch";
import fs from "fs";
import path from "path";
function uploadDir() {
const flagsArgs = process.argv.slice(2);
const dirPath = Object.values(flagsArgs)
.find((str) => str.includes("--path"))
?.split("=")[1];
if (!dirPath) {
console.log("Must pass a path");
return;
}
fs.readdir(dirPath, async function (err, files) {
//handling error
if (err) {
console.log(err);
return;
}
const filtered = files.filter((f) =>
[".jpg", ".png", ".svg"].some((x) => f.toLowerCase().includes(x))
);
const promises = filtered.map((file) => {
const fullPath = path.join(dirPath, file);
const formData = new FormData();
formData.append("file", `@${fullPath}`);
const form = new FormData();
form.append("file", fileFromSync(`${fullPath}`));
form.append("id", file);
const res = fetch(
"https://api.cloudflare.com/client/v4/accounts/0bd5ed1a4e347b9ac9b7360771c49626/images/v1",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.CLOUDFLARE_TOKEN}`,
},
body: form,
}
);
return res;
});
const result = await Promise.all(promises);
result.forEach(async (r) => {
try {
const j = await r.json();
console.log(j);
} catch (err) {
console.warn(`error uploading: ${err}. Skipping...`);
}
});
});
}
function renameFiles() {
const flagsArgs = process.argv.slice(2);
const dirPath = Object.values(flagsArgs)
.find((str) => str.includes("--path"))
?.split("=")[1];
if (!dirPath) {
console.log("Must pass a path");
return;
}
fs.readdir(dirPath, function (err, files) {
//handling error
const filtered = files.filter((f) =>
[".jpg", ".png", ".svg"].some((x) => f.toLowerCase().includes(x))
);
filtered.forEach((fileName) => {
const newFileName = fileName.split("_")[1];
const fullPath = path.join(dirPath, newFileName);
fs.renameSync(path.join(dirPath, fileName), fullPath);
});
if (err) {
console.log(err);
return;
}
});
}
// renameFiles();
uploadDir();