const deleteFilesFromS3 = async (fileKeys) => {
const s3 = new aws.S3({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: region,
});
// Iterate through fileKeys and delete each file from S3
for (const fileKey of fileKeys) {
const params = {
Bucket: "thenaturebeautyflower",
Key: fileKey,
};
try {
await s3.deleteObject(params).promise();
console.log(`File deleted successfully: ${fileKey}`);
} catch (error) {
console.error(`Error deleting file from S3: ${fileKey}`, error);
}
}
};
File deleted successfully: https://thenaturebeautyflower.s3.ap-south-1.amazonaws.com/pool/images/%20BERL%C3%8DN%20filter-1702962944491-3-Berlin.jpg ProductState.js:156 File deleted successfully: https://thenaturebeautyflower.s3.ap-south-1.amazonaws.com/pool/pdf/%20BERL%C3%8DN%20filter-1702962944491-BERLIN.pdf
but still image and pdf file is present in s3 console ?
const deleteFilesFromS3 = async (fileKeys) => {
// Creating an S3 client with AWS credentials
const s3 = new aws.S3({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: region,
});
// Specify the common prefix to be removed
const prefixToRemove = 'https://thenaturebeautyflower.s3.ap-south-1.amazonaws.com/';
// Iterate through fileKeys and delete each file from S3
for (const fileKey of fileKeys) {
// Remove the specified prefix from the file key
const keyWithoutPrefix = fileKey.replace(prefixToRemove, '');
// Determine the appropriate prefix based on the file type
const fileTypePrefix = fileKey.includes('images/') ? 'images/' : 'pdf/';
// Add the fileTypePrefix to the filename
const fileName = `${fileTypePrefix}${keyWithoutPrefix.split('/').pop()}`;
// Specify the parameters for deleting an object from S3
const params = {
Bucket: "thenaturebeautyflower",
Key: keyWithoutPrefix,
VersionId: 'null'
};
console.log(fileName);
try {
// Attempt to delete the object from S3
await s3.deleteObject(params).promise();
console.log(`File deleted successfully: ${fileKey}`);
} catch (error) {
console.error(`Error deleting file from S3: ${fileKey}`, error);
}
}
};
my mistake was that i was puuting complete address in filname under params which was wrong we should only contain a folder/filaname.extention only