-
Notifications
You must be signed in to change notification settings - Fork 38
/
save-podcast-image.js
62 lines (49 loc) · 1.19 KB
/
save-podcast-image.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
50
51
52
53
54
55
56
57
58
59
60
61
62
const sharp = require('sharp');
const fs = require('fs');
const fetch = require('node-fetch');
async function savePodcastImage(filename, url) {
try {
const stream = await fetch(url)
.then(res => res.body);
const path = `./public/img/podcast-images/${filename}.png`;
saveImage(path, stream);
} catch (e) {
console.log(e);
}
}
/**
* Use sharp to resize the images to our specified sizes
* as png and webp and saves a json file with the image data.
*
* @param {string} path
* @param {ReadableStream} imageStream
* @returns {Promise}
*/
async function saveImage(path, imageStream) {
return new Promise(function(resolve, reject) {
try {
console.log(path);
const transformer = sharp()
.resize({
width: 480,
height: 480
})
.png();
const output = fs.createWriteStream(path);
output.on('error', function (e) {
console.log(e);
reject(e);
});
output.on('finish', function () {
resolve();
})
imageStream
.pipe(transformer)
.pipe(output);
} catch (e) {
console.log(e);
reject(e);
}
});
}
module.exports = savePodcastImage;