Categories
JavaScript Answers

How to copy/move all objects in Amazon S3 from one prefix to other using the AWS SDK for Node.js?

Spread the love

To copy/move all objects in Amazon S3 from one prefix to other using the AWS SDK for Node.js, we use the coptObject method.

For instance, we write

const AWS = require("aws-sdk");
AWS.config.update({
  credentials: new AWS.Credentials("..."),
});
AWS.config.setPromisesDependency(require("bluebird"));
const s3 = new AWS.S3();

const bucketName = "bucketName";
const folderToMove = "folderToMove/";
const destinationFolder = "destinationFolder/";
try {
  const listObjectsResponse = await s3
    .listObjects({
      Bucket: bucketName,
      Prefix: folderToMove,
      Delimiter: "/",
    })
    .promise();

  const folderContentInfo = listObjectsResponse.Contents;
  const folderPrefix = listObjectsResponse.Prefix;

  await Promise.all(
    folderContentInfo.map(async (fileInfo) => {
      await s3
        .copyObject({
          Bucket: bucketName,
          CopySource: `${bucketName}/${fileInfo.Key}`,
          Key: `${destinationFolder}/${fileInfo.Key.replace(folderPrefix, "")}`,
        })
        .promise();

      await s3
        .deleteObject({
          Bucket: bucketName,
          Key: fileInfo.Key,
        })
        .promise();
    })
  );
} catch (err) {
  console.error(err);
}

to call folderContentInfo.map with a callback to return an array of promises that we get from copyObject.

We call copyObject with an object with the Bucket, the CopySource source path, and the Key to copy to.

Then we call delete object with an object with the Bucket and Key to delete the old object.

We call Promise.all with the array to run all the copy and delete operations.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *