Skip to content

Instantly share code, notes, and snippets.

@damianmcdonald
Last active November 23, 2022 10:45
Show Gist options
  • Save damianmcdonald/ef0310c06012d96df4288f7813f17ffc to your computer and use it in GitHub Desktop.
Save damianmcdonald/ef0310c06012d96df4288f7813f17ffc to your computer and use it in GitHub Desktop.
Node.js application which creates an S3 bucket and uploads a file with permissions and metadata

Overview

A Node.js application which creates an S3 bucket and uploads a file with permissions and metadata.

This example uses the createBucket and upload methods of the AWS SDK for JavaScript.

See API doocumentation for detailed information; https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html

To see the available parameters for the s3 upload method, see the paramObjects.js file.

Prerequisites

  • An AWS account with appropriate permissions to create the required resources
  • Node.js (v12+) and npm (v6+) installed and configured for use with AWS
  • Bash environment in which to execute the scripts
  • A jpg file in the executing directory called koala.jpg

Run the code

The code can be executed as follows:

node s3PutObject.js
{
"name": "s3PutObject",
"description": "A Node.js application which creates an S3 bucket and uploads a file with permissions and metadata.",
"version": "1.0.0",
"main": "s3PutObject.js",
"dependencies": {
"aws-sdk": "^2.610.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "DCORP",
"license": "ISC"
}
var params = {
Bucket: 'STRING_VALUE', /* required */
Key: 'STRING_VALUE', /* required */
ACL: private | public-read | public-read-write | authenticated-read | aws-exec-read | bucket-owner-read | bucket-owner-full-control,
Body: Buffer.from('...') || 'STRING_VALUE' || streamObject,
CacheControl: 'STRING_VALUE',
ContentDisposition: 'STRING_VALUE',
ContentEncoding: 'STRING_VALUE',
ContentLanguage: 'STRING_VALUE',
ContentLength: 'NUMBER_VALUE',
ContentMD5: 'STRING_VALUE',
ContentType: 'STRING_VALUE',
Expires: new Date || 'Wed Dec 31 1969 16:00:00 GMT-0800 (PST)' || 123456789,
GrantFullControl: 'STRING_VALUE',
GrantRead: 'STRING_VALUE',
GrantReadACP: 'STRING_VALUE',
GrantWriteACP: 'STRING_VALUE',
Metadata: {
'<MetadataKey>': 'STRING_VALUE',
/* '<MetadataKey>': ... */
},
ObjectLockLegalHoldStatus: ON | OFF,
ObjectLockMode: GOVERNANCE | COMPLIANCE,
ObjectLockRetainUntilDate: new Date || 'Wed Dec 31 1969 16:00:00 GMT-0800 (PST)' || 123456789,
RequestPayer: requester,
SSECustomerAlgorithm: 'STRING_VALUE',
SSECustomerKey: Buffer.from('...') || 'STRING_VALUE' /* Strings will be Base-64 encoded on your behalf */,
SSECustomerKeyMD5: 'STRING_VALUE',
SSEKMSEncryptionContext: 'STRING_VALUE',
SSEKMSKeyId: 'STRING_VALUE',
ServerSideEncryption: AES256 | aws:kms,
StorageClass: STANDARD | REDUCED_REDUNDANCY | STANDARD_IA | ONEZONE_IA | INTELLIGENT_TIERING | GLACIER | DEEP_ARCHIVE,
Tagging: 'STRING_VALUE',
WebsiteRedirectLocation: 'STRING_VALUE'
};
s3.putObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
// api reference: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html
// s3 acl reference: https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html
// get the refernce to the aws-sdk
const aws = require("aws-sdk");
const fs = require('fs');
// get reference to S3 client
const s3 = new aws.S3();
function random(low, high) {
return Math.round(Math.random() * (high - low) + low);
}
// global vars
const S3_BUCKET_NAME = "s3-putobject-test-" + random(10000, 50000);
const FILE_NAME = "koala.jpg";
const AWS_REGION = "eu-west-1"
async function createBucket() {
const params = {
Bucket: S3_BUCKET_NAME,
CreateBucketConfiguration: {
// Set your region here
LocationConstraint: AWS_REGION
}
};
await s3.createBucket(params, function(err, data) {
if (err) console.log(err, err.stack);
else console.log("Bucket Created Successfully", data.Location);
});
};
function uploadFile() {
// Read content from the file
const fileContent = fs.readFileSync(FILE_NAME);
// Setting up S3 upload parameters
const params = {
Bucket: S3_BUCKET_NAME,
Key: FILE_NAME, // File name you want to save as in S3
ACL: "private",
Body: fileContent,
ContentType: "image/jpeg",
// You can either assign an ACL or indivudual grants (not both!)
// GrantFullControl: "[email protected]",
// GrantFullControl: "id=canonical-user-id",
// GrantRead: "http://acs.amazonaws.com/groups/global/AuthenticatedUsers",
Metadata: {
'FirstName': 'Joe',
'LastName': 'Montana',
'Position': 'Quarterback',
'Team': 'San Francisco 49ers'
},
StorageClass: "STANDARD",
ServerSideEncryption: "AES256",
};
// Uploading files to the bucket
s3.upload(params, function(err, data) {
if (err) console.log(err, err.stack);
else console.log("File uploaded successfully.", data.Location);
});
};
// execute the create bucket function
createBucket(S3_BUCKET_NAME);
// execute the upload function
uploadFile(FILE_NAME);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment