-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimg.js
More file actions
44 lines (33 loc) · 1.24 KB
/
img.js
File metadata and controls
44 lines (33 loc) · 1.24 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
const axios = require('axios');
const fs = require('fs');
const path = require('path');
// http://pocketninjadesign.local/wp-content/uploads/2023/11/pocketninjadesign-adobe-xd-thumb-large.png
const imgUrl = "http://pocketninjadesign.local/wp-content/uploads/2023/11/pocketninjadesign-adobe-xd-thumb-large.png";
const localFilePath = "images/downloaded_image.png";
async function downloadImage(url, localPath) {
try {
const response = await axios({
method: 'GET',
url: url,
responseType: 'stream',
});
// Ensure that the local directory exists
const directory = path.dirname(localPath);
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory, { recursive: true });
}
// Pipe the response stream to a local file
response.data.pipe(fs.createWriteStream(localPath));
return new Promise((resolve, reject) => {
response.data.on('end', () => resolve());
response.data.on('error', (error) => reject(error));
});
}
catch (error) {
console.error('Error downloading image:', error.message);
throw error;
}
}
downloadImage(imgUrl, localFilePath)
.then(() => console.log('Image downloaded successfully.'))
.catch((error) => console.error('Failed to download image:', error));