nodejs aws s3 bucket delete item
To delete an item from an AWS S3 bucket using Node.js, you can follow these steps:
Install the AWS SDK: Use the npm package manager to install the AWS SDK for Node.js by running the command
npm install aws-sdk
.Configure AWS credentials: Set up your AWS credentials by creating a new AWS Access Key ID and Secret Access Key in the AWS Management Console. Then, configure your AWS credentials in your Node.js application using the
AWS.config.update
method. This should include theregion
andcredentials
properties.Create an S3 instance: Create an instance of the S3 class from the AWS SDK by calling
new AWS.S3()
.Delete the object: To delete an item from an S3 bucket, call the
deleteObject
method on the S3 instance. Provide theBucket
parameter with the name of your S3 bucket and theKey
parameter with the key of the item you want to delete.Handle the response: The
deleteObject
method returns a promise. You can use thethen
method to handle a successful delete operation and thecatch
method to handle any errors.
Here is an example code snippet that demonstrates the steps mentioned above:
const AWS = require('aws-sdk');
// Configure AWS credentials
AWS.config.update({
region: 'your-region',
credentials: {
accessKeyId: 'your-access-key-id',
secretAccessKey: 'your-secret-access-key'
}
});
// Create an S3 instance
const s3 = new AWS.S3();
// Delete object from S3 bucket
s3.deleteObject({
Bucket: 'your-bucket-name',
Key: 'your-object-key'
}).promise()
.then(() => {
console.log('Object deleted successfully');
})
.catch((error) => {
console.error('Error deleting object:', error);
});
Make sure to replace the placeholders (your-region
, your-access-key-id
, your-secret-access-key
, your-bucket-name
, and your-object-key
) with the appropriate values for your setup.