Streaming download allows you to download an object as streams in increments. If you want to download a large object or if the download requires a long period of time to complete, you can perform streaming download to download the object in increments.
Sample code
The following sample code provides an example on how to perform streaming download to download an object named exampleobject.txt from a bucket named examplebucket to the D:\localpath path in a local disk.
Note
When you use getStream
to download an object, Readable Stream
is returned and used to stream the object content.
const OSS = require('ali-oss');
const fs = require('fs');
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourRegion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Specify the name of the bucket.
bucket: 'examplebucket',
});
async function getStream () {
try {
// Specify the full path of the object. Do not include the bucket name in the full path.
const result = await client.getStream('exampleobject.txt');
console.log(result);
// Specify the full path of the local file. If a file that has the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path.
// If you do not specify a path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs.
const writeStream = fs.createWriteStream('D:\\localpath\\examplefile.txt');
result.stream.pipe(writeStream);
} catch (e) {
console.log(e);
}
}
getStream()