-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws.js
45 lines (41 loc) · 1.22 KB
/
aws.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
const aws = require("aws-sdk");
const fs = require("fs");
const s3 = new aws.S3({
accessKeyId: process.env.KEY,
secretAccessKey: process.env.SECRETKEY
});
async function uploadToS3(localFile, s3Folder) {
const fileStream = fs.createReadStream(localFile);
const fileName = localFile.split('/').pop();
const params = {
Bucket: process.env.BUCKET,
Key: `${s3Folder}/${fileName}`,
Body: fileStream
};
try {
const data = await s3.upload(params).promise();
console.log("Successfully uploaded file to S3:", data.Location);
} catch (err) {
console.log("Error uploading file:", err);
}
}
async function getFromS3(s3FilePath, localFolder) {
return new Promise((resolve, reject) => {
const params = {
Bucket: process.env.BUCKET,
Key: s3FilePath
};
s3.getObject(params, function(err, data) {
if (err) {
console.log("Error downloading file:", err);
reject(err);
} else {
const localFilePath = `${localFolder}/${s3FilePath.split('/').pop()}`;
fs.writeFileSync(localFilePath, data.Body);
console.log("S3 Downloaded to:", localFilePath);
resolve();
}
});
});
}
module.exports = { uploadToS3, getFromS3 };