-
Notifications
You must be signed in to change notification settings - Fork 21
/
image_cache.js
41 lines (33 loc) · 974 Bytes
/
image_cache.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
const got = require('got');
const fs = require('fs-extra');
const log = require('electron-log');
const { md5 } = require('./util/helpers');
const {remote, app} = require('electron');
function imageCache(url, callback) {
const root = (app ? app.getPath('userData').replace(/\\/g, '/') : remote.app.getPath('userData').replace(/\\/g, '/'));
const hash = md5(url);
const imagePath = `${root}/imageCache/${hash}.jpg`;
if (fs.pathExistsSync(imagePath)) {
if (callback) {
return callback(imagePath);
}
return imagePath;
}
log.info(`Caching image ${url}`);
const writeStream = fs.createWriteStream(imagePath);
const readStream = got.stream(url);
if (callback) {
readStream.pipe(writeStream);
writeStream.on('close', () => {
return callback(imagePath);
});
} else {
return new Promise(resolve => {
readStream.pipe(writeStream);
writeStream.on('close', () => {
return resolve(imagePath);
});
});
}
}
module.exports = imageCache;