Next: , Previous: , Up: Getting Started in Nodejs SDK   [Index]


5.5.4 Step 4—Write the Node.js Code

Create a new file named sample.js to contain the example code. Begin by adding the require function calls to include the SDK for JavaScript and uuid modules so that they are available for you to use.

Build a unique bucket name that is used to create an Amazon S3 bucket by appending a unique ID value to a recognizable prefix, in this case ’node-sdk-sample-’. You generate the unique ID by calling the uuid module. Then create a name for the Key parameter used to upload an object to the bucket.

Create a promise object to call the createBucket method of the AWS.S3 service object. On a successful response, create the parameters needed to upload text to the newly created bucket. Using another promise, call the putObject method to upload the text object to the bucket.

// Load the SDK and UUID
var AWS = require('aws-sdk');
var uuid = require('uuid');

// Create unique bucket name
var bucketName = 'node-sdk-sample-' + uuid.v4();
// Create name for uploaded object key
var keyName = 'hello_world.txt';

// Create a promise on S3 service object
var bucketPromise = new AWS.S3({apiVersion: '2006-03-01'}).createBucket({Bucket: bucketName}).promise();

// Handle promise fulfilled/rejected states
bucketPromise.then(
  function(data) {
    // Create params for putObject call
    var objectParams = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'};
    // Create object upload promise
    var uploadPromise = new AWS.S3({apiVersion: '2006-03-01'}).putObject(objectParams).promise();
    uploadPromise.then(
      function(data) {
        console.log("Successfully uploaded data to " + bucketName + "/" + keyName);
      });
}).catch(
  function(err) {
    console.error(err, err.stack);
});

This sample code can be found here on GitHub.