To simplify the organization and management of large numbers of objects, which can be difficult in a flat structure, Object Storage Service (OSS) offers the directory feature that simulates a folder structure.
Create a directory
The following code shows how to create a directory.
const OSS = require('ali-oss');
const client = new OSS({
// Set yourregion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// Get 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 set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Set bucket to the name of your bucket.
bucket: 'examplebucket',
});
async function putBuffer () {
try {
// Set 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();Delete a directory
Deleting a directory also deletes all its subdirectories and objects. Proceed with caution.
The following code shows how to delete the log/ directory and all objects in it.
const OSS = require('ali-oss');
const client = new OSS({
// Set yourregion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// Get 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 set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Set bucket to the name of your bucket.
bucket: 'yourbucketname'
});
// Handle failed requests to prevent promise.all from being interrupted and to return the failure reason and the name of the failed file.
async function handleDel(name, options) {
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);
}
// Delete the directory and all files in it.
deletePrefix('log/')References
Create a directory
For more information about the API operation that you can call to create a directory, see PutObject.
Delete a directory
For the complete sample code to delete a directory and all objects in it, see the GitHub example.
For more information about the API operation that you can call to delete a directory and all objects in the directory, see DeleteObject.