Streaming download lets you 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 download a file using getStream, the returned Readable Stream lets you 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. For example, if your bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourRegion',
// Obtain access credentials from environment variables. Before running this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
bucket: 'examplebucket',
});
async function getStream () {
try {
// Specify the full path of the object. The full path cannot include the bucket name.
const result = await client.getStream('exampleobject.txt');
console.log(result);
// Specify the full path of the local file. If the file exists, it is overwritten. If the file does not exist, it is created.
// If a local path is not specified, the file is saved to the project's local directory by default.
const writeStream = fs.createWriteStream('D:\\localpath\\examplefile.txt');
result.stream.pipe(writeStream);
} catch (e) {
console.log(e);
}
}
getStream()