用于在 Node.js 中使用 S3 和云存储的 @aws-sdk/client-s3 库
云存储已成为现代 Web 应用程序不可或缺的一部分。它们可以存储和传输任意大小的文件,提供高可用性和可扩展性。在 JavaScript (Node.js) 生态系统中,用于处理兼容 S3 的存储的最流行库之一是 @aws-sdk/client-s3——官方的第三代 AWS SDK。
该库提供了与 Amazon S3 以及任何兼容 S3 的对象存储(例如 MinIO、DigitalOcean Spaces、Yandex Object Storage、VK Cloud)交互的完整方法集。在本文中,我们将介绍安装、配置以及基本操作:上传、下载、删除和获取对象列表。
安装和导入
首先,通过 npm 安装该包:
npm install @aws-sdk/client-s3安装后,将必要的类导入到您的项目中:
const { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand, ListObjectsV2Command } = require('@aws-sdk/client-s3');配置 S3 客户端
要连接到 S3,需要创建一个客户端实例,指定区域、访问密钥,以及(对于第三方存储)可选的端点。
const s3Client = new S3Client({ region: 'ru-central1', // 您的存储区域 endpoint: 'https://storage.yandexcloud.net', // 用于 Yandex Object Storage credentials: { accessKeyId: 'YOUR_ACCESS_KEY', secretAccessKey: 'YOUR_SECRET_KEY' }});如果您直接使用 Amazon S3,则无需指定端点——SDK 会根据区域自动确定。对于使用 MinIO 的本地测试,请指定 endpoint: 'http://localhost:9000' 和 forcePathStyle: true。
S3 基本操作
1. 上传文件 (PutObject)
要上传文件到存储桶,请使用 PutObjectCommand 命令。数据可以作为字符串、缓冲区或流传递。
const uploadFile = async (bucketName, key, body) => { try { const command = new PutObjectCommand({ Bucket: bucketName, Key: key, Body: body, ContentType: 'text/plain' // 可选 }); const response = await s3Client.send(command); console.log('文件已上传:', response); } catch (err) { console.error('上传错误:', err); }};
// 使用示例uploadFile('my-bucket', 'hello.txt', '你好,世界!');2. 下载文件 (GetObject)
要获取存储中的对象,请使用 GetObjectCommand。数据以流的形式返回,可以转换为字符串或缓冲区。
const downloadFile = async (bucketName, key) => { try { const command = new GetObjectCommand({ Bucket: bucketName, Key: key }); const response = await s3Client.send(command); const str = await response.Body.transformToString('utf-8'); console.log('文件内容:', str); return str; } catch (err) { console.error('下载错误:', err); }};
// 使用示例downloadFile('my-bucket', 'hello.txt');3. 删除文件 (DeleteObject)
使用 DeleteObjectCommand 命令删除对象。
const deleteFile = async (bucketName, key) => { try { const command = new DeleteObjectCommand({ Bucket: bucketName, Key: key }); await s3Client.send(command); console.log('文件已删除'); } catch (err) { console.error('删除错误:', err); }};
deleteFile('my-bucket', 'hello.txt');4. 获取对象列表 (ListObjectsV2)
要列出存储桶中的所有对象,请使用