-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch-images.js
38 lines (33 loc) · 1.08 KB
/
fetch-images.js
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
const fs = require("fs");
const https = require("https");
const imageUrls = JSON.parse(fs.readFileSync("images.json"));
const baseUrl = "https://static.wixstatic.com/";
imageUrls.map(relUrl => {
let fileName = relUrl.split("/")[1];
fetchImage(relUrl, fileName);
});
function fetchImage(relUrl, fileName) {
if (fs.existsSync(fileName)) {
console.log(`File already exists.. skipping: ${fileName}`);
return;
}
https
.get(`${baseUrl}${relUrl}`, resp => {
let data = "";
resp.setEncoding("binary");
// A chunk of data has been recieved.
resp.on("data", chunk => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on("end", () => {
fs.writeFile(fileName, data, "binary", e => {
if (e) throw e;
console.log(`Saved ${fileName}`);
});
});
})
.on("error", e => {
console.log("Error: " + e.message);
});
}