Rename objects (OSS SDK for Node.js)
Updated at:
OSS does not support renaming objects directly. To rename an object, perform a copy-then-delete operation: call CopyObject to create a new object with the desired name, then call DeleteObject to remove the source object.
Sample code
The following sample code shows how to rename an object named srcobject.txt to destobject.txt within examplebucket.
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables. Before running this code, ensure 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 renameObject() {
try {
// Copy the source object 'srcobject.txt' to a new destination object 'destobject.txt'.
const r = await client.copy('destobject.txt', 'srcobject.txt');
console.log ('Copied', r);
// Delete srcobject.txt.
const deleteResult = await client.delete('srcobject.txt');
console.log(deleteResult);
} catch (e) {
console.log(e);
}
}
renameObject();
Note
Renaming directories requires the same copy-then-delete approach, applied recursively to all objects and subdirectories.
References
For more information about the API operations for renaming an object, see CopyObject and DeleteObject.
Is this page helpful?