I want to do below operations into lambda function
- In S3 bucket contains file with some content & metadata
- I want to copy same file & upload same location with epoc time
I written node js code in lambda function to take file, rename it & upload again
all things working fine but it uploading blank file.
used below code:
try {
const listObjCom = new ListObjectsV2Command({
Bucket: 'MY_BUCKET',
Prefix: `/TEST`,
});
const listObjResponse = await s3.send(listObjCom);
console.log("Bucket Contents---", JSON.stringify(listObjResponse));
for await (const itm of listObjResponse.Contents){
console.log("File name---"+itm.Key);
if(itm.Key.includes("sample.json")){
let spiltedFileName = itm.Key.split(".");
console.log("spilted from filename1--->"+ spiltedFileName[0].toLowerCase());
console.log("spilted from filename2--->"+ spiltedFileName[1].toLowerCase());
//code to get epoc time
Date.prototype.toUnixTime = function() { return this.getTime()/1000|0 };
Date.time = function() { return new Date().toUnixTime(); }
let epocTime = Date.time();
console.log("EPOC Time---"+epocTime);
let newFileName = spiltedFileName[0].toLowerCase()+"_"+epocTime+"."+spiltedFileName[1].toLowerCase();
console.log("File name after concate---"+newFileName);
const bucketParams = {
Bucket: 'MY_BUCKET',
CopySource: '/test' + '/' + newFileName,
Key: newFileName
};
const copyCommand = new CopyObjectCommand(bucketParams);
const copyResponse = await s3.send(copyCommand);
//const data = await s3.send(new PutObjectCommand(bucketParams));
console.log(
"Successfully uploaded File with New Name: " +
bucketParams.Bucket +
"/" +
bucketParams.newFileName
);
}
}
}catch (error) {
console.error("Error:" + event['custId'], error.message, error.stack);
}
Above code uploads blank file with epoc time. no metadata were attached to new file. Can anyone tell me what is issue here?
Update:
Found solution for this. I used GetObjectCommand to get all content of file & passed those content in body of bucket params like
const bucketParams = {
Bucket: event['bucket'],
Body: JSON.stringify(rawData),
Key: newFileName
};