通过 getObjectV2 方法可以从指定桶中下载对象。在使用此接口之前,确保拥有对此对象的读访问权限。
tos:GetObject
权限,具体操作,请参见权限配置指南。tos:GetObjectVersion
权限,具体操作,请参见权限配置指南。以下代码用于下载桶的对象到内存。
// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入 import { TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: process.env['TOS_ACCESS_KEY'], accessKeySecret: process.env['TOS_SECRET_KEY'], region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,"Provide your region" 填写为 cn-beijing。 endpoint: "Provide your endpoint", // 填写域名地址 }); function handleError(error) { if (error instanceof TosClientError) { console.log('Client Err Msg:', error.message); console.log('Client Err Stack:', error.stack); } else if (error instanceof TosServerError) { console.log('Request ID:', error.requestId); console.log('Response Status Code:', error.statusCode); console.log('Response Header:', error.headers); console.log('Response Err Code:', error.code); console.log('Response Err Msg:', error.message); } else { console.log('unexpected exception, message: ', error); } } async function main() { try { const bucketName = 'node-sdk-test-bucket'; // 目标桶 const objectName = 'example_dir/example.txt'; // 目标对象 // 返回 data.content 为 stream const { data: { content }, } = await client.getObjectV2({ bucket: bucketName, key: objectName, }); // 获取返回的 stream 中的所有内容 let allContent = Buffer.from([]); for await (const chunk of content) { allContent = Buffer.concat([allContent, chunk]); } console.log('object size:', allContent.length); // 如果对象是一串文字,可以 toString 解析 console.log('data string:', allContent.toString()); } catch (error) { handleError(error); } } main();
以下代码用于从 TOS 中下载数据到指定的本地文件路径。
// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入 import { TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: process.env['TOS_ACCESS_KEY'], accessKeySecret: process.env['TOS_SECRET_KEY'], region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,"Provide your region" 填写为 cn-beijing。 endpoint: "Provide your endpoint", // 填写域名地址 }); function handleError(error) { if (error instanceof TosClientError) { console.log('Client Err Msg:', error.message); console.log('Client Err Stack:', error.stack); } else if (error instanceof TosServerError) { console.log('Request ID:', error.requestId); console.log('Response Status Code:', error.statusCode); console.log('Response Header:', error.headers); console.log('Response Err Code:', error.code); console.log('Response Err Msg:', error.message); } else { console.log('unexpected exception, message: ', error); } } async function main() { try { const bucketName = 'node-sdk-test-bucket'; // 目标桶 const objectName = 'example_dir/example.txt'; // 目标对象 // 下载文件到指定的路径,示例中下载文件到 ./example_dir/example.txt const filePath = './example_dir/example.txt'; await client.getObjectToFile({ bucket: bucketName, key: objectName, filePath, }); } catch (error) { handleError(error); } } main();
以下代码用于下载桶中的对象,并重写 HTTP 响应头。
// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入 import { TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: process.env['TOS_ACCESS_KEY'], accessKeySecret: process.env['TOS_SECRET_KEY'], region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,则 "Provide your region" 填写为 cn-beijing。 endpoint: "Provide your endpoint", // 填写域名地址 }); function handleError(error) { if (error instanceof TosClientError) { console.log('Client Err Msg:', error.message); console.log('Client Err Stack:', error.stack); } else if (error instanceof TosServerError) { console.log('Request ID:', error.requestId); console.log('Response Status Code:', error.statusCode); console.log('Response Header:', error.headers); console.log('Response Err Code:', error.code); console.log('Response Err Msg:', error.message); } else { console.log('unexpected exception, message: ', error); } } async function main() { try { const bucketName = 'node-sdk-test-bucket'; // 目标桶 const objectName = 'example_dir/example.txt'; // 目标对象 // 返回 data.content 为 stream const { data: { content }, headers, } = await client.getObjectV2({ bucket: bucketName, key: objectName, responseContentType: 'application/json', responseContentEncoding: 'deflate', }); // 获取返回的 stream 中的所有内容 let allContent = Buffer.from([]); for await (const chunk of content) { allContent = Buffer.concat([allContent, chunk]); } console.log('object size:', allContent.length); // 如果对象是一串文字,可以 toString 解析 console.log('data string:', allContent.toString()); console.log('getObjectV2 response ContentType: ', headers['content-type']); console.log('getObjectV2 response ContentEncoding: ', headers['content-encoding']); console.log('getObjectV2 response Content-Length: ', headers['content-length']); } catch (error) { handleError(error); } } main();
下载时可通过 dataTransferStatusChange
参数接收下载进度,代码示例如下。
// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入 import { DataTransferType, TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: process.env['TOS_ACCESS_KEY'], accessKeySecret: process.env['TOS_SECRET_KEY'], region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,则 "Provide your region" 填写为 cn-beijing。 endpoint: "Provide your endpoint", // 填写域名地址 }); function handleError(error) { if (error instanceof TosClientError) { console.log('Client Err Msg:', error.message); console.log('Client Err Stack:', error.stack); } else if (error instanceof TosServerError) { console.log('Request ID:', error.requestId); console.log('Response Status Code:', error.statusCode); console.log('Response Header:', error.headers); console.log('Response Err Code:', error.code); console.log('Response Err Msg:', error.message); } else { console.log('unexpected exception, message: ', error); } } async function main() { try { const bucketName = 'node-sdk-test-bucket'; // 目标桶 const objectName = 'example_dir/example.txt'; // 目标对象 // 返回 data.content 为 stream const { data: { content }, } = await client.getObjectV2({ bucket: bucketName, key: objectName, // 通过自定义方式设置回调函数查看下载进度 dataTransferStatusChange: (event) => { if (event.type === DataTransferType.Started) { console.log('Data Transfer Started'); } else if (event.type === DataTransferType.Rw) { const percent = ((event.consumedBytes / event.totalBytes) * 100).toFixed(2); console.log(`Once Read:${event.rwOnceBytes},ConsumerBytes/TotalBytes: ${event.consumedBytes}/${event.totalBytes},${percent}%`); } else if (event.type === DataTransferType.Succeed) { const percent = ((event.consumedBytes / event.totalBytes) * 100).toFixed(2); console.log(`Data Transfer Succeed, ConsumerBytes/TotalBytes:${event.consumedBytes}/${event.totalBytes},${percent}%`); } else if (event.type === DataTransferType.Failed) { console.log('Data Transfer Failed'); } }, }); // 获取返回的 stream 中的所有内容 let allContent = Buffer.from([]); for await (const chunk of content) { allContent = Buffer.concat([allContent, chunk]); } console.log('object size:', allContent.length); // 如果对象是一串文字,可以 toString 解析 console.log('data string:', allContent.toString()); } catch (error) { handleError(error); } } main();
下载对象时可以通过客户端使用 rateLimiter
参数对下载数据所占用的带宽进行限制,代码如下所示。
// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入 import { DataTransferType, createDefaultRateLimiter, TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: process.env['TOS_ACCESS_KEY'], accessKeySecret: process.env['TOS_SECRET_KEY'], region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,则 "Provide your region" 填写为 cn-beijing。 endpoint: "Provide your endpoint", // 填写域名地址 }); function handleError(error) { if (error instanceof TosClientError) { console.log('Client Err Msg:', error.message); console.log('Client Err Stack:', error.stack); } else if (error instanceof TosServerError) { console.log('Request ID:', error.requestId); console.log('Response Status Code:', error.statusCode); console.log('Response Header:', error.headers); console.log('Response Err Code:', error.code); console.log('Response Err Msg:', error.message); } else { console.log('unexpected exception, message: ', error); } } async function main() { try { const bucketName = 'node-sdk-test-bucket'; // 目标桶 const objectName = 'example_dir/example.txt'; // 目标对象 const rateLimit1M = 1024 * 1024; // 返回 data.content 为 stream const { data: { content }, } = await client.getObjectV2({ bucket: bucketName, key: objectName, // 通过自定义方式设置回调函数查看下载进度 dataTransferStatusChange: (event) => { if (event.type === DataTransferType.Started) { console.log('Data Transfer Started'); } else if (event.type === DataTransferType.Rw) { const percent = ((event.consumedBytes / event.totalBytes) * 100).toFixed(2); console.log(`Once Read:${event.rwOnceBytes},ConsumerBytes/TotalBytes: ${event.consumedBytes}/${event.totalBytes},${percent}%`); } else if (event.type === DataTransferType.Succeed) { const percent = ((event.consumedBytes / event.totalBytes) * 100).toFixed(2); console.log(`Data Transfer Succeed, ConsumerBytes/TotalBytes:${event.consumedBytes}/${event.totalBytes},${percent}%`); } else if (event.type === DataTransferType.Failed) { console.log('Data Transfer Failed'); } }, // 下载对象并在客户端限制下载速度为 1M/s rateLimiter: createDefaultRateLimiter(rateLimit1M, rateLimit1M), }); // 获取返回的 stream 中的所有内容 let allContent = Buffer.from([]); for await (const chunk of content) { allContent = Buffer.concat([allContent, chunk]); } console.log('object size:', allContent.length); // 如果对象是一串文字,可以 toString 解析 console.log('data string:', allContent.toString()); } catch (error) { handleError(error); } } main();
关于下载对象的 API 文档,请参见 GetObject。