-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathupload.js
executable file
·81 lines (70 loc) · 2.09 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const fs = require("fs")
const path = require("path")
const mime = require("mime-types")
const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3")
const configDefaults = {
region: null,
dir: null,
bucket: null,
exclude: [],
accessKeyId: null,
secretAccessKey: null,
targetDir: null,
}
const getConfig = passedConfig => {
const receivedConfig = passedConfig || {}
return { ...configDefaults, ...receivedConfig }
}
const findFiles = directory => {
const files = fs.readdirSync(directory, { withFileTypes: true })
return files.reduce((mem, file) => {
const filepath = path.join(directory, file.name)
return file.isDirectory()
? [...mem, ...findFiles(filepath) ]
: [...mem, filepath]
}, [])
}
const getKey = (file, root, targetDir) => {
const filepath = path.relative(root, file)
return path.join(targetDir, filepath)
}
const uploadFile = (s3, config, file, key) => {
return fs.promises.readFile(file).then(data => {
const { bucket } = config
const basename = path.basename(file)
const contentType = mime.contentType(basename)
const params = { Bucket: bucket, Body: data, Key: key, ContentType: contentType }
return s3.send(new PutObjectCommand(params))
})
}
const upload = argv => {
const config = getConfig(argv)
const { region, accessKeyId, secretAccessKey, dir, exclude, targetDir } = config
const s3 = new S3Client({
region,
credentials: {
accessKeyId: accessKeyId || "unknown",
secretAccessKey: secretAccessKey || "unknown",
},
})
const directory = path.resolve(dir)
const files = findFiles(directory).filter(x => {
const ext = path.extname(x).slice(1)
return !exclude.includes(ext)
})
const promises = files.map(file => {
const key = getKey(file, directory, targetDir)
return uploadFile(s3, config, file, key)
.then(() => console.log("Uploaded", file))
})
return Promise.all(promises)
.then(() => {
console.log("Completed")
return process.exit(0)
})
.catch(error => {
console.error(error)
process.exit(1)
})
}
module.exports = upload