-
Notifications
You must be signed in to change notification settings - Fork 7
/
aws-upload.js
67 lines (59 loc) · 2.08 KB
/
aws-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
const AWS = require("aws-sdk");
const fs = require("fs");
const path = require("path");
const mime = require('mime');
const rootFolderName = process.env.BUILD_DIRECTORY || 'dist'
// configuration
const config = {
s3BucketName: process.env.BUCKET_NAME,
folderPath: `./${rootFolderName}` // path relative script's location
};
// initialize S3 client
const s3Config = {
signatureVersion: 'v4',
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
}
const s3 = new AWS.S3(s3Config);
//remove this log in production
// Github show **** instead of your keys(some privacy things), so dont panic if you see your password like that.
console.log('s3 config ', s3Config)
// resolve full folder path
const distFolderPath = path.join(__dirname, config.folderPath);
uploadDirectoryFiles(distFolderPath)
function uploadDirectoryFiles(distFolderPath) {
const files = fs.readdirSync(distFolderPath)
if (!files || files.length === 0) {
console.log(`provided folder '${distFolderPath}' is empty or does not exist.`);
return;
}
for (const fileName of files) {
// get the full path of the file
const filePath = path.join(distFolderPath, fileName);
// If it was directory recursively call this function again
if (fs.lstatSync(filePath).isDirectory()) {
uploadDirectoryFiles(filePath)
continue;
}
uploadFile(filePath, fileName)
}
}
function uploadFile(filePath, fileName) {
const relativeFilePath = `${__dirname}/${rootFolderName}/`
const fileKey = filePath.replace(relativeFilePath, '')
console.log({fileName, filePath, fileKey})
const fileContent = fs.readFileSync(filePath)
// upload file to S3
const ContentType = mime.getType(filePath)
s3.putObject({
Bucket: config.s3BucketName,
Key: fileKey,
Body: fileContent,
ContentType
}, (err, res) => {
if (err) {
return console.log("Error uploading file ", err)
}
console.log(`Successfully uploaded '${fileKey}'!`, {res});
});
}