Streaming download retrieves an object as a Readable stream in increments rather than loading it entirely into memory. Use this approach when downloading large objects, when the download requires a long period of time to complete, or when you want to pipe the content directly to a file or another writable destination.
Prerequisites
Before you begin, ensure that you have:
An OSS bucket with the object you want to download
The
ali-ossnpm package installedOSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETset as environment variables
Download an object as a stream
The following example downloads exampleobject.txt from examplebucket and saves it to a local file using getStream.
Note:getStreamreturns aReadablestream on theresult.streamproperty. Pipe it to any writable destination to process the file content as a stream.
const OSS = require('ali-oss');
const fs = require('fs');
const client = new OSS({
// Set region to the region where your bucket is located.
// Example: oss-cn-hangzhou for the China (Hangzhou) region.
region: 'yourRegion',
// Load credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this code.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
bucket: 'examplebucket',
});
async function downloadAsStream() {
try {
// Specify the full path of the object. Do not include the bucket name.
const result = await client.getStream('exampleobject.txt');
// Pipe the stream to a local file.
// If the file already exists, it is overwritten. If it does not exist, it is created.
// If you omit the path, the file is saved to the project directory.
const writeStream = fs.createWriteStream('D:\\localpath\\examplefile.txt');
result.stream.pipe(writeStream);
} catch (e) {
console.log(e);
}
}
downloadAsStream();Replace the following placeholders with actual values:
| Placeholder | Description | Example |
|---|---|---|
yourRegion | The region where your bucket is located | oss-cn-hangzhou |
examplebucket | The name of your bucket | my-bucket |
exampleobject.txt | The full path of the object (excluding the bucket name) | logs/app.log |
D:\\localpath\\examplefile.txt | The local destination path | ./downloads/app.log |