Copying Objects in Batches (SDK for Node.js)
If you have any questions during development, post them on the Issues page of GitHub.
Sample Code
This example copies objects from an OBS bucket to a destination bucket in batches. You can list objects whose names contain the specified prefix and copy them to the destination bucket in batches based on the specified concurrency. The destination keys are generated by replacing the original prefixes. Cross-bucket replication and intra-bucket backup are supported. This method is suitable for scenarios such as data migration and backup.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | // Import the OBS library. //Use npm for installation. const ObsClient = require("esdk-obs-nodejs"); // Use the source code for installation. // var ObsClient = require('./lib/obs'); // Create an ObsClient instance. const obsClient = new ObsClient({ // Obtain an AK and SK pair using environment variables (recommended) or import it in other ways. Using hard coding may result in leakage. // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html. access_key_id: process.env.ACCESS_KEY_ID, secret_access_key: process.env.SECRET_ACCESS_KEY, // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are not advised to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. // security_token: process.env.SECURITY_TOKEN, // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use. server: "https://obs.ap-southeast-1.myhuaweicloud.com" }); /** * Copying objects in batches * It is applicable to scenarios such as cross-bucket replication, intra-bucket backup, and version management. */ async function batchCopyObjects() { try { const sourceBucket = "source-bucket"; const destBucket = "dest-bucket"; const sourcePrefix = "source/"; const destPrefix = "backup/"; const params = { Bucket: sourceBucket, Prefix: sourcePrefix, EncodingType: "url", }; // List the source objects to be copied. let objectsToCopy = []; while (true) { const listResult = await obsClient.listObjects(params); if (listResult.CommonMsg.Status > 300) { console.log("List objects failed: Status=%d, Code=%s, Message=%s", listResult.CommonMsg.Status, listResult.CommonMsg.Code, listResult.CommonMsg.Message); return; } if (listResult.InterfaceResult.Contents && listResult.InterfaceResult.Contents.length > 0) { objectsToCopy = objectsToCopy.concat(listResult.InterfaceResult.Contents); } if (listResult.InterfaceResult.IsTruncated === "true") { params.Marker = listResult.InterfaceResult.NextMarker; } else { break; } } console.log(`Found ${objectsToCopy.length} objects, starting batch copy...`); // Use Promise.allSettled for parallel replication (limit the number of concurrent requests to avoid resource exhaustion). const concurrency = 5; // Number of concurrent requests let completed = 0; let successCount = 0; let failCount = 0; for (let i = 0; i < objectsToCopy.length; i += concurrency) { const batch = objectsToCopy.slice(i, i + concurrency); const copyPromises = batch.map(async (obj) => { // Destination object keys: Replace the prefixes. let destKey = obj.Key.replace(sourcePrefix, destPrefix); const copyParams = { Bucket: destBucket, Key: destKey, CopySource: `${sourceBucket}/${obj.Key}`, }; const result = await obsClient.copyObject(copyParams); if (result.CommonMsg.Status <= 300) { console.log(`[${++completed}/${objectsToCopy.length}] Object [${obj.Key}] -> [${destKey}] copied successfully`); return true; } else { console.log(`[${++completed}/${objectsToCopy.length}] Object [${obj.Key}] copy failed: ${result.CommonMsg.Message}`); return false; } }); const results = await Promise.allSettled(copyPromises); results.forEach((r) => { if (r.status === "fulfilled" && r.value) { successCount++; } else { failCount++; } }); } console.log(`Batch copy complete: ${successCount} succeeded, ${failCount} failed`); } catch (error) { console.log("Client exception:"); console.log(error); } } batchCopyObjects(); |
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot