@mahdi.golzar/fileuploader
Version:
FileUploader is a versatile tool designed for uploading files to various storage systems. It supports local storage, AWS S3, and Google Cloud Storage, with easy-to-use methods for file uploading.
75 lines (64 loc) • 2.35 kB
JavaScript
const fs = require('fs');
const path = require('path');
const AWS = require('aws-sdk');
const { Storage } = require('@google-cloud/storage');
class FileUploader {
constructor() {
this.storage = {
local: this.localStorage,
s3: this.s3Storage,
gcs: this.gcsStorage
};
}
useStorage(type, options) {
if (this.storage[type]) {
this.storageType = type;
this.storageOptions = options;
} else {
throw new Error('Unsupported storage type');
}
}
async upload(filePath, destination) {
if (!this.storageType) {
throw new Error('Storage type not set');
}
return this.storage[this.storageType].call(this, filePath, destination);
}
async localStorage(filePath, destination) {
const destPath = path.join(this.storageOptions.path, destination);
fs.copyFileSync(filePath, destPath);
console.log(`File uploaded to local storage at ${destPath}`);
}
async s3Storage(filePath, destination) {
const s3 = new AWS.S3({
accessKeyId: this.storageOptions.accessKeyId,
secretAccessKey: this.storageOptions.secretAccessKey,
region: this.storageOptions.region
});
const fileStream = fs.createReadStream(filePath);
const params = {
Bucket: this.storageOptions.bucketName,
Key: destination,
Body: fileStream
};
return s3.upload(params).promise().then(() => {
console.log(`File uploaded to S3 at ${destination}`);
}).catch(err => {
throw new Error(`Error uploading to S3: ${err.message}`);
});
}
async gcsStorage(filePath, destination) {
const storage = new Storage({
projectId: this.storageOptions.projectId,
keyFilename: this.storageOptions.keyFilename
});
const bucket = storage.bucket(this.storageOptions.bucketName);
const file = bucket.file(destination);
return bucket.upload(filePath, { destination }).then(() => {
console.log(`File uploaded to GCS at ${destination}`);
}).catch(err => {
throw new Error(`Error uploading to GCS: ${err.message}`);
});
}
}
module.exports = FileUploader;