leadsender_s3
Version:
Простой клиент для работы с S3-хранилищем. Позволяет загружать, скачивать и просматривать файлы в папках.
139 lines (113 loc) • 5.13 kB
JavaScript
const fs = require('fs');
const {
S3Client,
PutObjectCommand,
GetObjectCommand,
ListObjectsV2Command
} = require("@aws-sdk/client-s3");
const mime = require("mime-types");
const path = require("node:path");
class Client {
constructor({endpoint, region, bucket, accessKeyId, secretAccessKey}) {
this.endpoint = endpoint;
this.region = region || 'ru1';
this.bucket = bucket;
this.accessKeyId = accessKeyId;
this.secretAccessKey = secretAccessKey;
this.client = new S3Client({
endpoint: endpoint, // Endpoint
region: region, // Оставляем пустым, если регион не требуется
tls: true, // Использовать HTTPS (если endpoint начинается с https://)
credentials: {
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
},
});
}
static create(params) {
return new Client(params); // Возвращаем новый экземпляр класса
}
async uploadFile(filePath, folderPath, public_file = false) {
// Чтение файла асинхронно
const fileContent = fs.readFileSync(filePath);
// Убедимся, что путь к папке заканчивается на "/"
if (!folderPath.endsWith('/') && folderPath !== '') {
folderPath += '/';
}
const key = folderPath + path.basename(filePath);
// Определяем MIME-тип на основе расширения файла
const contentType = mime.lookup(key);
const additionalParams = {};
if (public_file) {
additionalParams.ACL = 'public-read';
}
// Параметры для загрузки файла
const params = {
Bucket: this.bucket,
Key: key,
Body: fileContent,
ContentType: contentType, // Автоматически определённый MIME-тип
...additionalParams, // Добавляем дополнительные параметры, если они переданы
};
// Создаем команду и отправляем её
const response = await this.client.send(new PutObjectCommand(params));
console.log("Файл успешно загружен:", {
url: `${this.endpoint}/${this.bucket}/${key}`,
key: key,
bucket: this.bucket,
contentType: contentType, // Логируем определённый MIME-тип
eTag: response.ETag, // ETag может быть полезен для проверки целостности файла
metadata: response.$metadata,
});
}
async downloadFile(key, downloadPath) {
const params = {
Bucket: this.bucket,
Key: key,
};
const {Body} = await this.client.send(new GetObjectCommand(params));
// Создаем поток для записи файла
const writeStream = fs.createWriteStream(downloadPath + '/' + key.split('/').pop());
// Записываем данные в файл
Body.pipe(writeStream);
console.log("Файл успешно скачан:", {
key: key,
bucket: this.bucket,
path: downloadPath,
});
}
async listFilesInFolder(folderPath) {
// Убедимся, что путь к папке заканчивается на "/"
if (!folderPath.endsWith('/') && folderPath !== '') {
folderPath += '/';
}
// Параметры для запроса списка объектов
const params = {
Bucket: this.bucket,
Prefix: folderPath, // Префикс для фильтрации объектов
Delimiter: '/', // Разделитель для имитации папок
};
// Выполняем запрос к S3
const response = await this.client.send(new ListObjectsV2Command(params));
// Если объектов нет, возвращаем пустой массив
if (!response?.CommonPrefixes?.length === 0) {
console.log("Папка пуста:", {
bucket: this.bucket,
folderPath: folderPath,
});
return [];
}
let files = [];
// Возвращаем список файлов (исключая "папки")
for (const item of (response?.CommonPrefixes || []).concat(response?.Contents || [])) {
files.push({
key: item?.Prefix || item?.Key,
fileName: item?.Key, // Извлекаем имя файла
size: item?.Size, // Размер файла
lastModified: item?.LastModified, // Дата последнего изменения
});
}
return files;
}
}
module.exports = Client;