Amazon Simple Storage Service (S3) is a cloud storage service. It is object storage here we can save any type of data that will be stored in the form of objects and can be retrieved from anywhere over the internet. We can handle all our items using the AWS console, it provides 99.99 % availability and 99.999% durability. You can read more here.
First let’s make our S3 bucket with the help of AWS console, sign-in to your console and then search for S3 in the search bar on the top and click on it.
;
const fs = require(‘fs’);
const AWSCredentials = {
accessKey: ‘YOUR_ACCESS_KEY’,
secret: ‘YOUR_SECRET_KEY’,
bucketName: ‘YOUR_S3_BUCKET_NAME’
};
const s3 = new AWS.S3({
accessKeyId: AWSCredentials.accessKey,
secretAccessKey: AWSCredentials.secret
});
const uploadToS3 = (fileName) => {
// Read content from the file
const fileContent = fs.readFileSync(fileName);
// Setting up S3 upload parameters
const params = {
Bucket: AWSCredentials.bucketName,
Key: fileName,
Body: fileContent
};
// Uploading files to the bucket
s3.upload(params, function(err, data) {
if (err) {
throw err;
}
console.log(File uploaded successfully. ${data.Location}
);
});
};
uploadToS3(“file.jpg”); // file to upload
Let’s see how this code works.
First, we are loading our node module and creating a configuration object.
const AWS = require(‘aws-sdk’);
const fs = require(‘fs’);
const AWSCredentials = {
accessKey: ‘YOUR_ACCESS_KEY’,
secret: ‘YOUR_SECRET_KEY’,
bucketName: ‘YOUR_S3_BUCKET_NAME’
};
Copy your access key and secret from the credentials files and paste it here. Put the bucket name in the configuration file. Then, we are creating a S3 object by providing it the access key and secret.
const s3 = new AWS.S3({
accessKeyId: AWSCredentials.accessKey,
secretAccessKey: AWSCredentials.secret
});
Then, we are creating a function to upload the file in S3 bucket. The function takes file name as an input and expect the file to present in the same foler where our code is.
First, we are reading the file as a Buffer using the following
code.
const fileContent = fs.readFileSync(fileName);
Then, we are creating an object with buffer, file name and bucket name and passing it in the upload() function.
Let’s run the code and check it’s output.
node app.js
This should return the following response.
File uploaded successfully. https://cfgdemo.s3.amazonaws.com/file.jpg
You can view the file in the S3 bucket as well.
Then, we are creating an object with buffer, file name and bucket name and passing it in the upload() function.
Let’s run the code and check it’s output.
node app.js
This should return the following response.
File uploaded successfully. https://cfgdemo.s3.amazonaws.com/file.jpg
You can view the file in the S3 bucket as well.
Then create bucket using the option:
Top comments (0)