To use an Amazon S3 bucket in a Node.js application, you can utilize the AWS SDK for JavaScript. Here's a step-by-step guide:
1. Install the AWS SDK
Run the following command to install the AWS SDK:
bashnpm install aws-sdk
2. Set Up AWS Credentials
You need to provide your AWS access key, secret key, and region. There are multiple ways to do this:
Option 1: Environment Variables
Set the following environment variables in your system or .env file:
plaintextAWS_ACCESS_KEY_ID=your-access-key AWS_SECRET_ACCESS_KEY=your-secret-key AWS_REGION=your-region
Option 2: AWS Config File
Add credentials to the ~/.aws/credentials file:
plaintext[default] aws_access_key_id=your-access-key aws_secret_access_key=your-secret-key
3. Write Node.js Code to Interact with S3
Here’s an example of common S3 operations:
a. Initialize S3 Client
javascript
const AWS = require('aws-sdk');
// Initialize S3 client
const s3 = new AWS.S3({
region: process.env.AWS_REGION, // Use environment variables
});
b. Upload a File to S3
javascript
const fs = require('fs');
const uploadFile = async (bucketName, filePath, key) => {
try {
const fileContent = fs.readFileSync(filePath);
const params = {
Bucket: bucketName,
Key: key, // File name in S3
Body: fileContent,
};
const data = await s3.upload(params).promise();
console.log(`File uploaded successfully. ${data.Location}`);
} catch (error) {
console.error('Error uploading file:', error);
}
};
// Usage
uploadFile('your-bucket-name', './path-to-your-file.txt', 'file.txt');
c. Download a File from S3
javascript
const downloadFile = async (bucketName, key, downloadPath) => {
try {
const params = {
Bucket: bucketName,
Key: key, // File name in S3
};
const data = await s3.getObject(params).promise();
fs.writeFileSync(downloadPath, data.Body);
console.log(`File downloaded successfully to ${downloadPath}`);
} catch (error) {
console.error('Error downloading file:', error);
}
};
// Usage
downloadFile('your-bucket-name', 'file.txt', './downloaded-file.txt');
d. List Files in an S3 Bucket
javascript
const listFiles = async (bucketName) => {
try {
const params = {
Bucket: bucketName,
};
const data = await s3.listObjectsV2(params).promise();
console.log('Files in bucket:');
data.Contents.forEach((file) => {
console.log(file.Key);
});
} catch (error) {
console.error('Error listing files:', error);
}
};
// Usage
listFiles('your-bucket-name');
e. Delete a File from S3
javascript
const deleteFile = async (bucketName, key) => {
try {
const params = {
Bucket: bucketName,
Key: key,
};
await s3.deleteObject(params).promise();
console.log(`File deleted successfully: ${key}`);
} catch (error) {
console.error('Error deleting file:', error);
}
};
// Usage
deleteFile('your-bucket-name', 'file.txt');
4. Best Practices
- Use IAM Roles: For production environments, use IAM roles instead of hardcoding credentials.
- Use Environment Variables: Store sensitive data in environment variables or a secure secrets manager.
- Set Permissions: Ensure the S3 bucket has the correct permissions to allow access for your application.
5. Error Handling
Always handle errors gracefully. For example:
javascript
try {
// S3 operation
} catch (error) {
if (error.code === 'NoSuchBucket') {
console.error('Bucket does not exist.');
} else {
console.error('An error occurred:', error.message);
}
}
Let me know if you'd like help with a specific use case or additional features like generating pre-signed URLs, handling large files, or setting up event-based triggers!
- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
Comments
Post a Comment