-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinstaPic.js
49 lines (43 loc) · 1.26 KB
/
instaPic.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
39
40
41
42
43
44
45
46
47
48
49
const axios = require("axios");
const cheerio = require("cheerio");
const fs = require("fs");
async function downloadImageFromUrl(imageUrl, destinationPath) {
const response = await axios({
method: "GET",
url: imageUrl,
responseType: "stream",
});
const writer = fs.createWriteStream(destinationPath);
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on("finish", resolve);
writer.on("error", reject);
});
}
async function getImageUrlFromInstagramPost(url) {
try {
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const imageUrl = $('meta[property="og:image"]').attr("content");
return imageUrl;
} catch (error) {
console.error("Error retrieving image URL:", error);
return null;
}
}
async function downloadAndSaveImage(url) {
try {
const imageUrl = await getImageUrlFromInstagramPost(url);
if (imageUrl) {
await downloadImageFromUrl(imageUrl, "downloads/groupPic.jpg");
console.log("Image downloaded successfully!");
return "downloads/groupPic.jpg"; // Return the path of the downloaded image
}
} catch (error) {
console.error("Error:", error);
}
}
module.exports = {
downloadAndSaveImage,
getImageUrlFromInstagramPost,
};