O OSS oferece diretórios que simulam uma estrutura de pastas. Isso facilita a organização, a localização e a execução de operações em lote em grandes quantidades de objetos.
Criar um diretório
O código a seguir mostra como criar um diretório.
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region where your bucket is located. For example, use 'oss-cn-hangzhou' for the China (Hangzhou) region.
region: 'yourregion',
// Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Specify the bucket name.
bucket: 'examplebucket',
});
async function putBuffer () {
try {
// Specify the directory name. The name must end with a forward slash (/).
const result = await client.put('exampledir/', new Buffer(''));
console.log(result);
} catch (e) {
console.log(e);
}
}
putBuffer();
Excluir um diretório
Excluir um diretório também remove todos os seus subdiretórios e objetos. Proceda com cautela.
O código a seguir mostra como excluir o diretório log/ e todos os objetos nele contidos.
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region where your bucket is located. For example, for the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Specify the bucket name.
bucket: 'yourbucketname'
});
// Handle a failed request to prevent `promise.all` from being interrupted. Returns the failure reason and the name of the object that failed to be deleted.
async function handleDel(name, options) {
try {
await client.delete(name);
} catch (error) {
error.failObjectName = name;
return error;
}
}
// Delete multiple objects.
async function deletePrefix(prefix) {
const list = await client.list({
prefix: prefix,
});
list.objects = list.objects || [];
const result = await Promise.all(list.objects.map((v) => handleDel(v.name)));
console.log(result);
}
// Delete the directory and all objects in it.
deletePrefix('log/')
Referências
-
Criar uma pasta
Para mais informações sobre a operação de API usada para criar pastas, consulte PutObject.
-
Excluir um diretório
Para ver o código de exemplo completo sobre como excluir um diretório e todos os objetos nele contidos, consulte o exemplo no GitHub.
Para mais detalhes sobre a operação de API usada para excluir pastas e todos os seus arquivos, consulte DeleteObject.