-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.js
113 lines (91 loc) · 2.54 KB
/
file.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* Usage */
/*
const file = require('./file.js')
const imageDirectory = 'tmp_images'
const images = {}
let loadImages = false
// Somewhere on each possible image url
if (url && String(url).match(/^https:\/\/.*\/.*\.(jpg|png|svg|jpeg)($|\?)/i)) {
const filename = file.getFilename(url)
const id = makeUid(url)
const filepath = file.getFullPath(imageDirectory, filename)
if (!images[id]) images[id] = {
filename,
url,
filepath
}
loadImages = true
// Assign filepath as the new value for the image
obj[imgField] = filepath
}
// After processing all fields
if (loadImages) await downloadImages(images)
async function downloadImages(images) {
file.createDirectory(imageDirectory)
let exists = 0
const download = []
Object.keys(images).forEach(async (id) => {
const { filename, filepath } = images[id]
if (!file.exists(filepath)) {
download.push(images[id])
} else exists++
})
ISDEV && console.log(`${exists} images already exists and ${download.length} to download`)
if (download.length) {
await pMap(download, async ({ filename, url, filepath }) => {
await file.download(url, filepath)
ISDEV && console.log(`Downloaded ${filename}`)
}, {
concurrency: os.cpus * 2
})
}
}
*/
const https = require('https')
const fs = require('fs-extra')
const path = require('path')
const TMPDIR = '.temp/downloads'
let tmpCount = 0
function createDirectory(dir) {
const pwd = path.resolve(dir)
if (!fs.existsSync(pwd)) fs.mkdirs(pwd)
return pwd
}
createDirectory(TMPDIR)
function getFullPath(dir, filename) {
return path.resolve(dir, filename)
}
function getFilename(url, regex) {
let name = url.replace(/%2F/g, '/').split('/').pop().replace(/\#(.*?)$/, '').replace(/\?(.*?)$/, '')
return regex ? name.replace(regex, '$1$2') : name
}
function exists(filepath) {
return fs.existsSync(filepath)
}
function downloadIfNotExists(url, absPath) {
if (!url || !path || exists(absPath)) return
return download(url, absPath)
}
function download(url, absPath) {
return new Promise(function(resolve) {
const tmpPath = getFullPath(TMPDIR, `${++tmpCount}.tmp`)
const file = fs.createWriteStream(tmpPath)
const request = https.get(url, (response) => {
response.pipe(file)
file.on('finish', () => {
file.close()
fs.rename(tmpPath, absPath, resolve)
})
}).on('error', (err) => {
console.error(err.message)
fs.unlink(String(tmpPath), resolve)
})
})
}
module.exports = {
createDirectory,
getFullPath,
getFilename,
exists,
download
}