Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a file from one folder to another folder in s3

First I'm trying to copy the file into other folder and unable to delete it. How I can delete the file only if the file is copied to the destination folder.

    const s3Params = {
        Bucket: bucket,
        CopySource: bucket + '/' + objectkey,
        Key: 'processed-data/' + objectkey
    };

    function copyFile() {
        s3.copyObject(s3Params, function (err, data) {
            if (err) {
                console.log(err);
            }
            else {
                deleteFile();
            }
        });
    }

    function deleteFile() {
        s3.deleteObject(s3Params, function (err, data) {
            if (err) {
                console.log(err, err.stack);
                logs.push(err, err.stack);
            }
            else {
                console.log("File moved successfully");
                log.push("File moved successfully");
            }
        });    
    }
like image 905
Bhargav Teja Avatar asked Jan 01 '23 12:01

Bhargav Teja


1 Answers

Since you haven't shared with us the complete code, I created the following lambda function example which copies a specific file from source folder to destination folder and then delete the file from the source folder. as much as I can tell it looks like your lambda were missing some parameters and some promises.

Code snippet :

const aws = require('aws-sdk');
const s3 = new aws.S3();

const bucketName = 'Bucket Name'
const sourceFolder = 'Source Folder'
const fileName = 'File Name with extention'
const destFolder = 'Destination Folder'


const s3Params = {
        Bucket: bucketName,
        CopySource: `${bucketName}/${sourceFolder}/${fileName}`,
        Key: `${destFolder}/${fileName}`
    };

function copyFile() {
  return s3.copyObject(s3Params).promise();
    }


function deleteFile() {
     return s3.deleteObject({  Bucket: bucketName, Key: `${sourceFolder}/${fileName}` }).promise();
}


exports.handler = async (event, context, callback) => {

try{
  await copyFile().then(r => deleteFile());
  console.log('All good')
}
catch(ex){ console.log(`Failed with the following exception : ${ex}`)

}


};
like image 160
Amit Baranes Avatar answered Jan 12 '23 15:01

Amit Baranes