Created
January 25, 2024 19:07
-
-
Save jclosure/bd68c62fa3d42a1479710b63ab812811 to your computer and use it in GitHub Desktop.
Just a simple ES6 uploader/downloader for S3 objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ACCESS_KEY_ID = "mykey_id"; | |
var SECRET_ACCESS_KEY = "mykey_secret"; | |
var REGION = 'us-east-1'; | |
var ENDPOINT = 'http://127.0.0.1:9000'; | |
import { S3 } from '@aws-sdk/client-s3'; | |
import * as fs from 'fs'; | |
class FileClient { | |
constructor(bucket) { | |
this.bucket = bucket; | |
this.s3 = new S3({ | |
region: REGION, | |
credentials: { | |
accessKeyId: ACCESS_KEY_ID, | |
secretAccessKey: SECRET_ACCESS_KEY, | |
}, | |
endpoint: ENDPOINT, | |
s3ForcePathStyle: 'true', // needed with minio | |
signatureVersion: 'v4' | |
}); | |
} | |
UploadFile(key, path) { | |
const stream = fs.createReadStream(path); | |
var params = {Bucket: this.bucket, Key: key, Body: stream}; | |
this.s3.putObject(params, function(err, data) { | |
if (err) | |
console.log(err) | |
else | |
console.log(`Successfully uploaded file: ${path} to key: ${key}`); | |
}); | |
} | |
DownloadFile(key, path) { | |
var params = {Bucket: this.bucket, Key: key}; | |
// const streamToBuffer = (stream) => new Promise((resolve, reject) => { | |
// const chunks = []; | |
// stream.on('data', (chunk) => chunks.push(chunk)); | |
// stream.on('error', reject); | |
// stream.on('end', () => resolve(Buffer.concat(chunks))); | |
// }); | |
var file = fs.createWriteStream(path); | |
const streamToFile = (stream) => new Promise((resolve, reject) => { | |
stream.on('data', (chunk) => file.write(chunk)); | |
stream.on('error', reject); | |
stream.on('end', () => {file.end() && resolve()}); | |
}); | |
this.s3.getObject(params, function(err, data){ | |
streamToFile(data.Body).then(result => { | |
console.log(`file: ${key} downloaded to: ${path}`); | |
}).catch(err => { | |
console.log(err) | |
}) | |
}); | |
} | |
} | |
export { FileClient }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment