Amazon AWS SDK Getting Started Manual

Type
Getting Started Manual
AWS SDK for Node.js
Getting Started Guide
Version 0.9.1-pre.2 : Preview
Amazon Web Services
AWS SDK for Node.js Getting Started Guide
AWS SDK for Node.js: Getting Started Guide
Amazon Web Services
Copyright © 2013 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.
The following are trademarks of Amazon Web Services, Inc.: Amazon, Amazon Web Services Design, AWS,
Amazon CloudFront, Cloudfront, Amazon DevPay, DynamoDB, ElastiCache, Amazon EC2, Amazon Elastic
Compute Cloud, Amazon Glacier, Kindle, Kindle Fire, AWS Marketplace Design, Mechanical Turk, Amazon
Redshift, Amazon Route 53, Amazon S3, Amazon VPC. In addition, Amazon.com graphics, logos, page
headers, button icons, scripts, and service names are trademarks, or trade dress of Amazon in the U.S.
and/or other countries. Amazon's trademarks and trade dress may not be used in connection with any
product or service that is not Amazon's, in any manner that is likely to cause confusion among customers,
or in any manner that disparages or discredits Amazon.
All other trademarks not owned by Amazon are the property of their respective owners, who may or may
not be affiliated with, connected to, or sponsored by Amazon.
AWS SDK for Node.js Getting Started Guide
AWS SDK for Node.js ............................................................................................................................. 1
AWS Account and Credentials ............................................................................................................... 2
Configuration Guide ................................................................................................................................ 4
Services .................................................................................................................................................. 7
Making Requests .................................................................................................................................... 9
Examples .............................................................................................................................................. 14
Version 0.9.1-pre.2 : Preview
4
AWS SDK for Node.js Getting Started Guide
AWS SDK for Node.js
The official JavaScript implementation of the AWS SDK for Node.js.
Installing
To use the AWS SDK for Node.js, you must have an AWS account. If you do not yet have an AWS
account, see AWS Account and Credentials (p.2) for instructions on how to sign up.
The preferred way to install the AWS SDK for Node.js is to use the npm package manager for Node.js.
Simply type the following into a terminal window:
npm install aws-sdk
Note
Installing the aws-sdk npm package on Windows may display errors while trying to install the
optional dependency for libxmljs.This error can be safely ignored.
Usage
After you've installed the SDK, you can require the AWS package in your node application using require:
var AWS = require('aws-sdk');
Here is a quick example that makes some requests against Amazon S3 with the SDK:
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
/**
* Don't hard-code your credentials!
Version 0.9.1-pre.2 : Preview
1
AWS SDK for Node.js Getting Started Guide
Installing
* Load them from disk or your environment instead.
*/
// AWS.config.update({accessKeyId: 'AKID', secretAccessKey: 'SECRET'});
// Instead, do this:
AWS.config.loadFromPath('./path/to/credentials.json');
// Set your region for future requests.
AWS.config.update({region: 'us-east-1'});
// Create a bucket and put something in it.
var s3 = new AWS.S3();
s3.client.createBucket({Bucket: 'myBucket'}).done(function(resp) {
var data = {Bucket: 'myBucket', Key: 'myKey', Body: 'Hello!'};
s3.client.putObject(data).done(function(resp) {
console.log("Successfully uploaded data to myBucket/myKey");
});
});
License
This SDK is distributed under the Apache License, Version 2.0.
Copyright 2012. Amazon Web Services, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License.You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is
distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing permissions and limitations under
the License.
AWS Account and Credentials
To access AWS, you will need to sign up for an AWS account.
To sign up for an AWS account
1. Go to http://aws.amazon.com, and then click Sign Up.
2. Follow the on-screen instructions.
Part of the sign-up procedure involves receiving a phone call and entering a PIN using the phone
keypad.
AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view
your current account activity and manage your account by going to http://aws.amazon.com and clicking
My Account/Console.
Version 0.9.1-pre.2 : Preview
2
AWS SDK for Node.js Getting Started Guide
License
When you sign up, AWS provides you with security credentials that are specific to your account.Two of
these credentials, your access key ID and your secret key, are used by the SDK whenever it accesses
the services provided by AWS.The security credentials authenticate requests to the service and identify
you as the sender of a request.The following list shows examples of these credentials.
Access Key ID Example: AKIAIOSFODNN7EXAMPLE
Secret Access Key Example: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
To view your AWS access credentials
1. Go to the Amazon Web Services website at http://aws.amazon.com.
2. Click My Account/Console, and then click Security Credentials.
3. Under Your Account, click Security Credentials.
4. In the spaces provided, type your user name and password, and then click Sign in using our secure
server.
5. Under Access Credentials, on the Access Keys tab, your access key ID is displayed.To view your
secret key, under Secret Access Key, click Show.
Your secret key must remain a secret that is known only to you and AWS. Keep it confidential in order
to protect your account. Store it securely in a safe place, and never email it. Do not share it outside your
organization, even if an inquiry appears to come from AWS or Amazon.com. No one who legitimately
represents Amazon will ever ask you for your secret key.
The credentials that are returned from the sign-up process are your root credentials. In general, we
recommend that you do not use your root credentials for most interactions with AWS.Your root credentials
provide complete access to your AWS account including your billing information.You should always keep
your root credentials as secure as possible and use them only when necessary. Instead of using your
root credentials, we recommend that you create an IAM user with only the permissions necessary to
perform the desired AWS tasks. For information about how to create an IAM user, go to the Identity and
Access Management documentation.
Version 0.9.1-pre.2 : Preview
3
AWS SDK for Node.js Getting Started Guide
AWS Account and Credentials
Configuration Guide
The Configuration Object
Configuration in the SDK can be done in two ways:
1. Global configuration on AWS.config, or,
2. Passing extra configuration to a service object
Setting global configuration with AWS.config is often easier to get up and running with, but service level
configuration can provide much more control over your requests. Both of these configuration mechanisms
are discussed.
Global Configuration (AWS.config)
By default, you can set global configuration by updating the AWS.config object with new settings.The
most common settings are:
accessKeyId, secretAccessKey, sessionToken — for credential management
region — to set the region for requests
sslEnabled — whether SSL is enabled or not
maxRetries — to control the number of retries for a request
The only things you need to set in order to use the SDK are credentials and the region value. Let's discuss
how to do that.
Setting AWS Credentials
Note
Remember, if you set your AWS credentials in your environment variables, the AWS SDK for
Node.js will automatically detect them, and you will not need to perform any manual credential
configuration in your application.
Version 0.9.1-pre.2 : Preview
4
AWS SDK for Node.js Getting Started Guide
The Configuration Object
Credentials are the most important thing you need to set when using any AWS SDK. Credentials can be
set globally on the AWS.config object or per service by passing the credential information to the service
object directly.
There are a few ways to load credentials. Here they are, in order of recommendation:
1. Loaded from environment variables,
2. Loaded from a JSON file on disk,
3. Loaded from EC2 metadata service,
4. Hardcoded in your application
We recommend you not hard-code your AWS credentials in your application; however, it is reasonable
to temporarily hard-code credential information in small personal scripts or for testing purposes.
Credentials from Environment Variables
By default, the AWS SDK for Node.js will automatically detect AWS credentials set in your environment
and use them for requests.This means that if you properly set your environment variables, you do not
need to manage credentials in your application at all.
The keys that the SDK looks for are as follows:
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN (optional)
Alternately, the SDK can accept the AMAZON_ prefix instead:
AMAZON_ACCESS_KEY_ID, AMAZON_SECRET_ACCESS_KEY, AMAZON_SESSION_TOKEN (optional)
Credentials from Disk
You can also load configuration and credentials from disk using AWS.config.loadFromPath by passing
a file to a JSON document containing the configuration data. For example, if you had a file named
'config.json' with the contents:
{ "accessKeyId": "akid", "secretAccessKey": "secret", "region": "us-east-1" }
You can load the JSON data using the command:
AWS.config.loadFromPath('./config.json');
Note that the loadFromPath method clobbers all existing configuration on the object. If you are adding
extra configuration, make sure you add it after this call.
Hard-Coding Credentials
Note
We recommend you not hard-code credentials inside an application. Use this method only for
small personal scripts or for testing purposes.
Version 0.9.1-pre.2 : Preview
5
AWS SDK for Node.js Getting Started Guide
Setting AWS Credentials
You can hard-code credentials by passing the credential information to the configuration object using
AWS.config.update():
AWS.config.update({accessKeyId: 'akid', secretAccessKey: 'secret'});
Setting the Region
The AWS SDK for Node.js doesn't select the region by default.You can choose a region similarly to
setting credentials by either loading from disk or using AWS.config.update():
AWS.config.update({region: 'us-west-1'});
Service-Specific Configuration
Occasionally, you might want to apply configuration only to one service. For instance, you want to use
multiple EC2 objects in different regions.You can do this by passing configuration data directly to the
service object constructor:
var ec2 = new AWS.EC2({region: 'ap-southeast-2', maxRetries: 15});
Note that the constructor takes all of the same configuration data as the AWS.config object described
above, including credential information.
Immutable Configuration Data
Global configuration changes apply to all requests for all newly created services. Any newly created
service will merge its local options on top of the global configuration data at the time of creation.This
means that any future updates to the global AWS.config object will not apply to existing service objects.
These services would have to be manually updated with the new configuration data, or recreated using
the following command (assuming an existing s3 service object):
s3 = new AWS.S3(s3.config);
Version 0.9.1-pre.2 : Preview
6
AWS SDK for Node.js Getting Started Guide
Setting the Region
Services
Supported Services
Here's the list of supported service objects:
AWS.AutoScaling
AWS.CloudFormation
AWS.CloudFront
AWS.CloudSearch
AWS.CloudWatch
AWS.DataPipeline
AWS.DirectConnect
AWS.DynamoDB
AWS.EC2
AWS.ElastiCache
AWS.ElasticBeanstalk
AWS.ElasticTranscoder
AWS.ELB
AWS.EMR
AWS.Glacier
AWS.IAM
AWS.ImportExport
AWS.OpsWorks
AWS.RDS
AWS.Redshift
AWS.Route53
AWS.S3
AWS.SES
AWS.SimpleDB
AWS.SimpleWorkflow
AWS.SNS
AWS.SQS
Version 0.9.1-pre.2 : Preview
7
AWS SDK for Node.js Getting Started Guide
Supported Services
AWS.StorageGateway
AWS.STS
Each service object in the SDK currently provides low-level access to every API call in the respective
AWS service.The full list of methods and their parameters are documented in the complete API reference
(linked from each service name in the above list).
Constructing a Service
Each service can be constructed with runtime configuration data that is specific to that service object.
The service-specific configuration data will be merged on top of global configuration, so there is no need
to re-specify any global settings. For example, an EC2 object can be created for a specific region:
var ec2 = new EC2({region: 'us-west-2'});
This object will continue to use the globally provided credentials.
Passing Arguments to a Service Method
When calling a method to a service, you should pass parameters in as option values, similar to the way
configuration is passed. For example, to read an object for a given bucket and key in S3, you can pass
the following parameters to the getObject method:
s3.getObject({Bucket: 'bucketName', Key: 'keyName'});
Note that the full parameter documentation for each method is found in each service page in the complete
API reference documentation.
Version 0.9.1-pre.2 : Preview
8
AWS SDK for Node.js Getting Started Guide
Constructing a Service
Making Requests
Asynchronous Callbacks
All requests made through the SDK are asynchronous and use a callback interface. Each service method
that kicks off a request can accept a callback as the last parameter with the signature function(error,
data) { ... }.This callback will be called when the response or error data is available.
For example, the following service method can be called with a standard callback to retrieve the response
data or error:
new AWS.EC2().client.describeInstances(function(error, data) {
if (error) {
console.log(error); // an error occurred
} else {
console.log(data); // request succeeded
}
});
The error and data parameters are described in the Response Object section below.
Note that if you do not specify a callback, the operation will return an AWS.Request object that must be
manually sent using the send() method:
// create the AWS.Request object
var request = new AWS.EC2().client.describeInstances();
// register a callback to report on the data
request.on('success', function(resp) {
console.log(response.data); // log the successful data response
});
// send the request
request.send();
Version 0.9.1-pre.2 : Preview
9
AWS SDK for Node.js Getting Started Guide
Asynchronous Callbacks
The Response Object (AWS.Response)
The response object is passed into each callback function so that you can access response data.The
AWS.Response object that is passed in contains two important properties to get at this data:
data
error
When using the standard callback mechanism, the two properties will be made available as parameters
on the callback method in the form: function(error, data) { ... }
The data property
The response.data property contains the serialized object data retrieved from the service request. For
instance, for an Amazon DynamoDB listTables method call, the response data might look like this:
> response.data
{ TableNames:
[ 'table1', 'table2', ... ] }
The data property can be null if an error occurs (see below).
The error property
In the event of a service error (or transfer error), the response.error property will be filled with the
given error data in the form:
{ code: 'SHORT_UNIQUE_ERROR_CODE',
message: 'Some human readable error message' }
In the case of an error, the data property will be null. Note that if you handle events that can be in a
failure state, you should always check whether response.error is set before attempting to access the
response.data property.
The request Property
Access to the originating request object is available through this property. For example, to access the
parameters that were sent with a request:
s3.getObject({Bucket: 'bucket', Key: 'key'}).on('success', function(response)
{
console.log("Key was", response.request.params.Key);
}).send();
Version 0.9.1-pre.2 : Preview
10
AWS SDK for Node.js Getting Started Guide
The Response Object (AWS.Response)
Simplified Callback Method
Each operation supports a simplified callback that can be passed as the last parameter to any low-level
client operation.The callback function should accept an error parameter, followed by the data from
the response.
For example:
s3.client.listBuckets(function(error, data) {
if (err) {
console.log(error); // error is Response.error
} else {
console.log(data); // data is Response.data
}
});
Prints (assuming the request succeeded):
{ Owner: { ID: '...', DisplayName: '...' },
Buckets:
[ { Name: 'someBucketName', CreationDate: someCreationDate },
{ Name: 'otherBucketName', CreationDate: otherCreationDate } ],
RequestId: '...' }
The error and data parameters accepted are equivalent to the error and data properties discussed in
the AWS.Response response object section above.
If you are passing parameters to the operation, the callback should be placed after the parameters:
s3.client.getObject({Bucket: 'bucket', Key: 'key'}, function(err, data) {
// ...
});
AWS.Request Events
You can alternatively register callbacks on events provided by the AWS.Request object returned by each
low-level client operation method.This request object exposes the success, error, complete, and
httpData events, each taking a callback that accepts the response object.
Note that if you omit the simplified callback parameter on the operation method, you must call send()
on the returned request object in order to kick off the request to the remote server.
on('success', function(response) { ... })
This event triggers when a successful response from the server is returned.The response contains a
.data field with the serialized response data from the service.
For example:
Version 0.9.1-pre.2 : Preview
11
AWS SDK for Node.js Getting Started Guide
Simplified Callback Method
s3.client.listBuckets().done(function(response) {
console.log(response.data);
}).send();
Prints:
{ Owner: { ID: '...', DisplayName: '...' },
Buckets:
[ { Name: 'someBucketName', CreationDate: someCreationDate },
{ Name: 'otherBucketName', CreationDate: otherCreationDate } ],
RequestId: '...' }
on('error', function(error, response) { ... })
The error event works similarly to the success event, except that it triggers in the case of a request
failure. In this case, response.data will be null and the response.error field will be filled with the
error data. Note that the error object is also passed directly as the first parameter to the event:
s3.config.credentials.accessKeyId = 'invalid';
s3.client.listBuckets().fail(function(error, response) {
console.log(error);
// or:
console.log(response.error);
}).send();
Prints:
{ code: 'Forbidden', message: null }
on('complete', function(response) { ... })
The complete event triggers a callback in any final state of a request, i.e., both success and error.
Use this callback to handle any request cleanup that must be executed regardless of the success state.
Note that if you do intend to use response data inside of this callback, you must check for the presence
of response.data or response.error before attempting to access either property. For example:
request.on('complete', function(response) {
if (response.error) {
// an error occurred, handle it
} else {
// we can use response.data here
}
}).send();
Version 0.9.1-pre.2 : Preview
12
AWS SDK for Node.js Getting Started Guide
on('error', function(error, response) { ...
})
on('httpData', function(chunk, response) { ... })
Note
If you register a httpData callback, response.data will still contain serialized output for the
entire request. It will be your responsibility to remove the default 'httpData' listener if you do not
wish to have the extra parsing and memory overhead from the built-in handlers.
The httpData event is used to stream response data from the service packet-by-packet.This event is
mostly used for large responses, when it is inefficient (or impossible) to load the entire response into
memory.
Note that this event contains an extra chunk parameter containing the actual data passed on by the
server.
The always event triggers a callback in any final state of a request, i.e., both done and fail. Use this
callback to handle any request cleanup that must be executed regardless of the success state. Note that
if you do intend to use response data inside of this callback, you must check for the presence of
response.data or response.error before attempting to access either property. For example:
Multiple Callbacks and Chaining
You can register multiple callbacks on any request object.The callbacks can be registered for different
events, or all for the same event. In addition, you can chain callback registration, for example:
request.
on('success', function(response) {
console.log("Success!");
}).
on('error', function(response) {
console.log("Error!");
}).
on('complete', function() {
console.log("Always!");
}).
send();
The above example will print either "Success! Always!", or "Error! Always!", depending on whether the
request succeeded or not.
Version 0.9.1-pre.2 : Preview
13
AWS SDK for Node.js Getting Started Guide
on('httpData', function(chunk, response) {
... })
Examples
All of these examples assume that the AWS library is required, credentials are loaded via environment
variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY), and the region is set via
AWS.config.update({region: 'us-east-1'});.
The common preamble code can be summarized as follows:
var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
Amazon Simple Storage Service (Amazon S3)
Amazon S3: List All of Your Buckets (listBuckets)
The following example lists all buckets associated with your AWS account:
var s3 = new AWS.S3();
s3.client.listBuckets(function(err, data) {
for (var index in data.Buckets) {
var bucket = data.Buckets[index];
console.log("Bucket: ", bucket.Name, ' : ', bucket.CreationDate);
}
});
Amazon S3: Create a New Bucket and Object
(createBucket, putObject)
The following example puts the string 'Hello!' inside the object 'myKey' of bucket 'myBucket':
var s3 = new AWS.S3();
Version 0.9.1-pre.2 : Preview
14
AWS SDK for Node.js Getting Started Guide
Amazon Simple Storage Service (Amazon S3)
s3.client.createBucket({Bucket: 'myBucket'}, function() {
var data = {Bucket: 'myBucket', Key: 'myKey', Body: 'Hello!'};
s3.client.putObject(data, function() {
console.log("Successfully uploaded data to myBucket/myKey");
});
});
Amazon S3: Streaming Objects to Files on Disk
(getObject)
You can use the createReadStream() method on a request object to get a handle to a stream object
which supports piping raw HTTP body data to a file.This is especially useful when streaming objects to
streams like filesystem objects.The following example shows how you can stream an object from Amazon
S3 directly to a file on disk:
var s3 = new AWS.S3();
var params = {Bucket: 'myBucket', Key: 'myImageFile.jpg'};
var file = require('fs').createWriteStream('/path/to/file.jpg');
s3.client.getObject(params).createReadStream().pipe(file);
Alternatively, you can register an 'httpData' event listener on the request object to access each chunk of
data received across the wire (as Buffer objects):
var s3 = new AWS.S3();
var params = {Bucket: 'myBucket', Key: 'myImageFile.jpg'};
var file = require('fs').createWriteStream('/path/to/file.jpg');
s3.client.getObject(params).
on('httpData', function(chunk) { file.write(chunk); }).
on('httpDone', function() { file.end(); }).
send();
Amazon DynamoDB
Amazon DynamoDB: Listing Tables (listTables)
The following example will list all tables in a DynamoDB instance:
var db = new AWS.DynamoDB();
db.client.listTables(function(err, data) {
console.log(data.TableNames);
});
Version 0.9.1-pre.2 : Preview
15
AWS SDK for Node.js Getting Started Guide
Amazon S3: Streaming Objects to Files on Disk
(getObject)
  • Page 1 1
  • Page 2 2
  • Page 3 3
  • Page 4 4
  • Page 5 5
  • Page 6 6
  • Page 7 7
  • Page 8 8
  • Page 9 9
  • Page 10 10
  • Page 11 11
  • Page 12 12
  • Page 13 13
  • Page 14 14
  • Page 15 15
  • Page 16 16
  • Page 17 17
  • Page 18 18
  • Page 19 19

Amazon AWS SDK Getting Started Manual

Type
Getting Started Manual

Ask a question and I''ll find the answer in the document

Finding information in a document is now easier with AI