Let’s explore how to write a simple Node.js application that uses the S3 API to write data to the Scality S3 Server. If you do not have the S3 Server up and running yet, please visit the Docker Hub page to run it easily on your laptop. First we need to create a list of the libraries needed in a file called package.json. When the node package manager (npm) is run, it will download each library for the application. For this simple application, we will only need the aws-sdk library.
Save the following contents in package.json
{ "name": "myAPP", "version": "0.0.1", "dependencies": { "aws-sdk": "" } }
Now let’s begin coding the main application in a file called app.js with the following contents:
var aws = require('aws-sdk'); var ACCESS_KEY = process.env.ACCESS_KEY; var SECRET_KEY = process.env.SECRET_KEY; var ENDPOINT = process.env.ENDPOINT; var BUCKET = process.env.BUCKET; aws.config.update({ accessKeyId: ACCESS_KEY, secretAccessKey: SECRET_KEY }); var s3 = new aws.S3({ endpoint: ENDPOINT, s3ForcePathStyle: true, }); function upload() { params = { Bucket: BUCKET, Key: process.argv[2], Body: process.argv[3] }; s3.putObject(params, function(err, data) { if (err) { console.log('Error uploading data: ', err); } else { console.log("Successfully uploaded data to: " + BUCKET); } }); } if (ACCESS_KEY && SECRET_KEY && ENDPOINT && BUCKET && process.argv[2] && process.argv[3]) { console.log('Creating File: ' + process.argv[2] + ' with the following contents:\n\n' + process.argv[3] + '\n\n'); upload(); } else { console.log('\n[Error: Missing S3 credentials or arguments!\n'); }
This simple application will accept two arguments on the command-line. The first argument is for the file name and the second one is for the contents of the file. Think of it as a simple note taking application.
Now that the application is written, we can install the required libraries with npm.
npm install
Before the application is started, we need to set the S3 credentials, bucket, and endpoint in environment variables.
export ACCESS_KEY='accessKey1' export SECRET_KEY=’verySecreyKey1' export BUCKET='test' export ENDPOINT='http://127.0.0.1:8000'
Please ensure that the bucket specified in the BUCKET argument exists on the S3 Server. If it does not, please create it.
Now we can run the application to create a simple file called “my-message” with the contents of “Take out the trash at 1pm PST”
node app.js 'my-message' 'Take out the trash at 1pm PST'
You should now see the file on the S3 Server using your favorite S3 Client:
I hope that this tutorial will help you get started quickly to create wonderful applications that use the S3 API to store data on the Scality S3 Server. For more code samples for different SDKs, please visit the Scality S3 Server GitHub .