Exclua um único objeto, vários objetos por nome, objetos correspondentes a um prefixo ou um diretório inteiro.
Objetos excluídos não podem ser recuperados. Proceda com cautela.
Excluir um único arquivo
O código a seguir exclui um objeto chamado exampleobject.txt de um bucket chamado examplebucket:
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables. Before you run 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 deleteObject() {
try {
// Specify the full path of the object. The full path cannot contain the bucket name.
const result = await client.delete('exampleobject.txt');
console.log(result);
} catch (error) {
console.log(error);
}
}
deleteObject();
Excluir arquivos em lote
É possível excluir até 1.000 objetos por vez por nome, prefixo ou diretório.
A resposta de uma operação de exclusão em lote pode retornar em dois modos:
Modo detalhado: o corpo da resposta do OSS contém o resultado de cada objeto excluído. Este é o modo padrão.
Modo silencioso: o OSS não retorna corpo de resposta.
Também é possível configurar regras de ciclo de vida para excluir objetos automaticamente. Para mais informações, consulte Regras de ciclo de vida baseadas na última modificação.
Delete multiple objects with specified names
O código a seguir exclui vários objetos por nome:
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables. Before you run 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 deleteMulti() {
try {
// Specify the full paths of the objects to delete and set the response mode to verbose. The full paths cannot contain the bucket name.
// let result = await client.deleteMulti(['exampleobject-1', 'exampleobject-2', 'testfolder/sampleobject.txt']);
// console.log(result);
// Specify the full paths of the objects to delete and set the response mode to quiet. The full paths cannot contain the bucket name.
const result = await client.deleteMulti(['exampleobject-1', 'exampleobject-2', 'testfolder/sampleobject.txt'], {quiet: true});
console.log(result);
} catch (error) {
console.log(error);
}
}
deleteMulti();
Delete multiple objects with the specified object name prefix or in the specified directory
O código a seguir exclui objetos por prefixo ou remove um diretório inteiro:
Se o prefixo não for especificado ou estiver definido como NULL, todos os objetos no bucket serão excluídos. Defina os prefixos com atenção.
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables. Before you run 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',
});
// Handle failed requests to prevent promise.all from breaking, and return the failure reason and the failed file name.
async function handleDel(name) {
try {
await client.delete(name);
} catch (error) {
error.failObjectName = name;
return error;
}
}
// Delete multiple files.
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);
}
// To delete all objects that have the 'src' prefix, set prefix to 'src'. This deletes files such as 'src_file.txt', the 'src' folder, and all files within the 'src' folder.
deletePrefix('src');
// To delete only the 'src' folder and all files within it, set prefix to 'src/'.
// deletePrefix('src/');
Referências
Para obter o código de exemplo completo sobre como excluir um ou mais arquivos, consulte o exemplo no GitHub.
Para consultar a referência da API sobre a exclusão de um único arquivo, veja DeleteObject.
Para consultar a referência da API sobre a exclusão de vários arquivos, acesse DeleteMultipleObjects.