Use client.get() to download an object from a bucket to a local file.
Prerequisites
Before you begin, ensure that you have:
An OSS bucket with at least one object
The
ali-osspackage installed (npm install ali-oss)OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETset as environment variables
Store credentials in environment variables rather than hardcoding them in your source code. For production workloads, use Resource Access Management (RAM) roles instead of AccessKey credentials.
Sample code
The following example downloads exampleobject.txt from examplebucket and saves it to D:\localpath\examplefile.txt.
const OSS = require('ali-oss');
const client = new OSS({
// Set the region where the bucket is located. For example, oss-cn-hangzhou.
region: 'yourRegion',
// Read credentials from environment variables.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
bucket: 'examplebucket'
});
async function get() {
try {
// Specify the full path of the object and the full path of the local file.
// Do not include the bucket name in the object path.
// If the local file exists, it is overwritten. If it does not exist, it is created.
// If no local path is specified, the file is saved to the project directory.
const result = await client.get('exampleobject.txt', 'D:\\localpath\\examplefile.txt');
console.log(result);
} catch (e) {
console.log(e);
}
}
get();Parameters
client.get(name, localFilePath)
| Parameter | Type | Description |
|---|---|---|
name | string | Full path of the object to download. Do not include the bucket name. |
localFilePath | string | Full path of the local file to save the object to. If the file exists, it is overwritten. If it does not exist, it is created. If omitted, the file is saved to the project directory. |