O download por streaming permite baixar um objeto em fluxos incrementais. Se você precisa baixar um objeto grande ou se o download exige muito tempo para ser concluído, use o download por streaming para transferir o objeto em partes.
Código de exemplo
O código de exemplo a seguir mostra como baixar por streaming um objeto chamado exampleobject.txt de um bucket chamado examplebucket para o caminho D:\localpath em um disco local.
Nota
Ao baixar um arquivo com getStream, o Readable Stream retornado permite processar o conteúdo do arquivo como um fluxo.
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()