-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload.js
67 lines (52 loc) · 1.42 KB
/
upload.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
'use strict'
const fs = require('fs')
const path = require('path')
const s3 = new (require('aws-sdk')).S3()
const join = dir => filename => path.join(dir, filename)
const Bucket = 'pring.ca'
const ACL = 'public-read'
const getContentType = filepath => {
const [_, type] = filepath.match(/\.(html|css|js)$/) || []
return !type ? type : type === 'js' ? 'text/javascript' : `text/${type}`
}
const upload = (Key, Body) =>
s3.upload(
{
Bucket,
ACL,
Key,
Body,
ContentType: getContentType(Key),
},
{},
err => err && console.log(err),
)
const uploadAllFilesInDirectory = (directory, streamMap = new Map()) => {
fs.readdir(directory, (err, files) => {
files
.filter(file => /^[^\.]/.test(file))
.filter(file => file !== 'node_modules')
.map(join(directory))
.forEach(file => {
const readStream = fs.createReadStream(file)
readStream.on('error', err => {
streamMap.delete(file)
if (err.code === 'EISDIR') {
uploadAllFilesInDirectory(file, streamMap)
}
})
return streamMap.set(file, readStream)
})
})
}
const map = new Map()
uploadAllFilesInDirectory('./', map)
const uploadFromMap = map => {
if (!map.size) return
for (const [key, fileStream] of map) {
upload(key, fileStream)
map.delete(key)
}
setTimeout(uploadFromMap, 5000, map)
}
setImmediate(uploadFromMap, map)