-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.js
More file actions
38 lines (32 loc) · 977 Bytes
/
utils.js
File metadata and controls
38 lines (32 loc) · 977 Bytes
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
import axios from "axios";
import fs from "fs";
import path from "path";
export async function downloadImage(imageUrl) {
try {
const response = await axios({
url: imageUrl,
method: "GET",
responseType: "stream",
});
const filename = path.basename(imageUrl);
const localPath = path.join("/tmp", filename);
const downloadDir = path.dirname(localPath);
if (!fs.existsSync(downloadDir)) {
fs.mkdirSync(downloadDir, { recursive: true });
}
response.data.pipe(fs.createWriteStream(localPath));
return new Promise((resolve, reject) => {
response.data.on("end", () => {
console.log(`Image downloaded successfully: ${localPath}`);
resolve(localPath);
});
response.data.on("error", (err) => {
console.error("Error downloading image:", err);
reject(err);
});
});
} catch (error) {
console.error("Error downloading image:", error);
throw error;
}
}