

The Amazon SDK for JavaScript v2 has reached end-of-support. We recommend that you migrate to [Amazon SDK for JavaScript v3](https://docs.amazonaws.cn//sdk-for-javascript/v3/developer-guide/). For additional details and information on how to migrate, please refer to this [announcement](https://amazonaws-china.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-javascript-v2/).

# Getting Started with the Amazon SDK for JavaScript
Getting StartedNew Getting Started in a Browser Script[this text is ignored](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-browser.html)

Getting Started in a Browser Script has been rewritten to simplify the example and to access the Amazon Polly service to send text and return synthesized speech you can play in the browser. See [Getting Started in Browser Script](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-browser.html) for the new content.

The Amazon SDK for JavaScript provides access to web services in either browser scripts or Node.js. This section has two getting started exercises that show you how to work with the SDK for JavaScript in each of these JavaScript environments.

**Topics**
+ [

# Getting Started in a Browser Script
](getting-started-browser.md)
+ [

# Getting Started in Node.js
](getting-started-nodejs.md)

# Getting Started in a Browser Script


![\[JavaScript code example that applies to browser execution\]](http://docs.amazonaws.cn/en_us/sdk-for-javascript/v2/developer-guide/images/browsericon.png)

**This browser script example shows you:**
+ How to access Amazon services from a browser script using Amazon Cognito Identity.
+ How to turn text into synthesized speech using Amazon Polly.
+ How to use a presigner object to create a presigned URL.

## The Scenario


Amazon Polly is a cloud service that converts text into lifelike speech. You can use Amazon Polly to develop applications that increase engagement and accessibility. Amazon Polly supports multiple languages and includes a variety of lifelike voices. For more information about Amazon Polly, see the [https://docs.amazonaws.cn/polly/latest/dg/](https://docs.amazonaws.cn/polly/latest/dg/).

The example shows how to set up and run a simple browser script that takes text you enter, sends that text to Amazon Polly, and then returns the URL of the synthesized audio of the text for you to play. The browser script uses Amazon Cognito Identity to provide credentials needed to access Amazon services. You will see the basic patterns for loading and using the SDK for JavaScript in browser scripts.

**Note**  
Playback of the synthesized speech in this example depends on running in a browser that supports HTML 5 audio.

![\[Illustration of how a browser script interacts with Amazon Cognito Identity and Amazon Polly services\]](http://docs.amazonaws.cn/en_us/sdk-for-javascript/v2/developer-guide/images/images_bjs/browserscenario.png)


The browser script uses the SDK for JavaScript to synthesize text by using these APIs:
+ [https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/AWS/CognitoIdentityCredentials.html](https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/AWS/CognitoIdentityCredentials.html) constructor
+ [https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/AWS/Polly/Presigner.html](https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/AWS/Polly/Presigner.html) constructor
+ [https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/AWS/Polly/Presigner.html#getSynthesizeSpeechUrl-property](https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/AWS/Polly/Presigner.html#getSynthesizeSpeechUrl-property)

## Step 1: Create an Amazon Cognito Identity Pool


In this exercise, you create and use an Amazon Cognito identity pool to provide unauthenticated access to your browser script for the Amazon Polly service. Creating an identity pool also creates two IAM roles, one to support users authenticated by an identity provider and the other to support unauthenticated guest users.

In this exercise, we will only work with the unauthenticated user role to keep the task focused. You can integrate support for an identity provider and authenticated users later. For more information about adding a Amazon Cognito identity pool, see [Tutorial: Creating an identity pool](https://docs.amazonaws.cn/cognito/latest/developerguide/tutorial-create-identity-pool.html) in the *Amazon Cognito Developer Guide*.

**To create an Amazon Cognito identity pool**

1. Sign in to the Amazon Web Services Management Console and open the Amazon Cognito console at [https://console.amazonaws.cn/cognito/](https://console.amazonaws.cn/cognito/).

1. In the left navigation pane, choose **Identity pools**.

1. Choose **Create identity pool**.

1. In **Configure identity pool trust**, choose **Guest access** for user authentication.

1. In **Configure permissions**, choose **Create a new IAM role** and enter a name (for example, *getStartedRole*) in the **IAM role name**.

1. In **Configure properties**, enter a name (for example, *getStartedPool*) in **Identity pool name**.

1. In **Review and create**, confirm the selections that you made for your new identity pool. Select **Edit** to return to the wizard and change any settings. When you're done, select **Create identity pool**.

1. Note the **Identity pool ID** and the **Region** of the newly created Amazon Cognito identity pool. You need these values to replace *IDENTITY\$1POOL\$1ID* and *REGION* in [Step 4: Write the Browser Script](#getting-started-browser-write-sample).

After you create your Amazon Cognito identity pool, you're ready to add permissions for Amazon Polly that are needed by your browser script.

## Step 2: Add a Policy to the Created IAM Role


To enable browser script access to Amazon Polly for speech synthesis, use the unauthenticated IAM role created for your Amazon Cognito identity pool. This requires you to add an IAM policy to the role. For more information about modifying IAM roles, see [Modifying a role permissions policy](https://docs.amazonaws.cn/IAM/latest/UserGuide/roles-managingrole-editing-console.html#roles-modify_permissions-policy) in the *IAM User Guide*.

**To add an Amazon Polly policy to the IAM role associated with unauthenticated users**

1. Sign in to the Amazon Web Services Management Console and open the IAM console at [https://console.amazonaws.cn/iam/](https://console.amazonaws.cn/iam/).

1. In the left navigation pane, choose **Roles**.

1. Choose the name of the role that you want to modify (for example, *getStartedRole*), and then choose the **Permissions** tab.

1. Choose **Add permissions** and then choose **Attach policies**.

1. In the **Add permissions** page for this role, find and then select the check box for **AmazonPollyReadOnly**.
**Note**  
You can use this process to enable access to any Amazon service.

1. Choose **Add permissions**.

After you create your Amazon Cognito identity pool and add permissions for Amazon Polly to your IAM role for unauthenticated users, you are ready to build the webpage and browser script.

## Step 3: Create the HTML Page


The sample app consists of a single HTML page that contains the user interface and browser script. To begin, create an HTML document and copy the following contents into it. The page includes an input field and button, an `<audio>` element to play the synthesized speech, and a `<p>` element to display messages. (Note that the full example is shown at the bottom of this page.)

For more information on the `<audio>` element, see [audio](https://www.w3schools.com/tags/tag_audio.asp).

```
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Amazon SDK for JavaScript - Browser Getting Started Application</title>
  </head>

  <body>
    <div id="textToSynth">
      <input autofocus size="23" type="text" id="textEntry" value="It's very good to meet you."/>
      <button class="btn default" onClick="speakText()">Synthesize</button>
      <p id="result">Enter text above then click Synthesize</p>
    </div>
    <audio id="audioPlayback" controls>
      <source id="audioSource" type="audio/mp3" src="">
    </audio>
    <!-- (script elements go here) -->
 </body>
</html>
```

Save the HTML file, naming it `polly.html`. After you have created the user interface for the application, you're ready to add the browser script code that runs the application.

## Step 4: Write the Browser Script


The first thing to do when creating the browser script is to include the SDK for JavaScript by adding a `<script>` element after the `<audio>` element in the page. To find the current SDK\$1VERSION\$1NUMBER, see the API Reference for the SDK for JavaScript at [Amazon SDK for JavaScript API Reference Guide.](https://docs.amazonaws.cn/AWSJavaScriptSDK/latest/)

```
<script src="https://sdk.amazonaws.com/js/aws-sdk-SDK_VERSION_NUMBER.min.js"></script>
```

Then add a new `<script type="text/javascript">` element after the SDK entry. You'll add the browser script to this element. Set the Amazon Region and credentials for the SDK. Next, create a function named `speakText()` that will be invoked as an event handler by the button.

To synthesize speech with Amazon Polly, you must provide a variety of parameters including the sound format of the output, the sampling rate, the ID of the voice to use, and the text to play back. When you initially create the parameters, set the `Text:` parameter to an empty string; the `Text:` parameter will be set to the value you retrieve from the `<input>` element in the webpage. Replace *IDENTITY\$1POOL\$1ID* and *REGION* in the following code with values noted in [Step 1: Create an Amazon Cognito Identity Pool](#getting-started-browser-create-identity-pool).

```
    <script type="text/javascript">

        // Initialize the Amazon Cognito credentials provider
        AWS.config.region = 'REGION';
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId: 'IDENTITY_POOL_ID'});

        // Function invoked by button click
        function speakText() {
            // Create the JSON parameters for getSynthesizeSpeechUrl
            var speechParams = {
                OutputFormat: "mp3",
                SampleRate: "16000",
                Text: "",
                TextType: "text",
                VoiceId: "Matthew"
            };
            speechParams.Text = document.getElementById("textEntry").value;
```

Amazon Polly returns synthesized speech as an audio stream. The easiest way to play that audio in a browser is to have Amazon Polly make the audio available at a presigned URL you can then set as the `src` attribute of the `<audio>` element in the webpage.

Create a new `AWS.Polly` service object. Then create the `AWS.Polly.Presigner` object you'll use to create the presigned URL from which the synthesized speech audio can be retrieved. You must pass the speech parameters that you defined as well as the `AWS.Polly` service object that you created to the `AWS.Polly.Presigner` constructor.

After you create the presigner object, call the `getSynthesizeSpeechUrl` method of that object, passing the speech parameters. If successful, this method returns the URL of the synthesized speech, which you then assign to the `<audio>` element for playback.

```
            // Create the Polly service object and presigner object
            var polly = new AWS.Polly({apiVersion: '2016-06-10'});
            var signer = new AWS.Polly.Presigner(speechParams, polly)

            // Create presigned URL of synthesized speech file
            signer.getSynthesizeSpeechUrl(speechParams, function(error, url) {
            if (error) {
                document.getElementById('result').innerHTML = error;
            } else {
                document.getElementById('audioSource').src = url;
                document.getElementById('audioPlayback').load();
                document.getElementById('result').innerHTML = "Speech ready to play.";
            }
          });
        }
    </script>
```

## Step 5: Run the Sample


To run the sample app, load `polly.html` into a web browser. This is what the browser presentation should resemble.

![\[Web application browser interface\]](http://docs.amazonaws.cn/en_us/sdk-for-javascript/v2/developer-guide/images/browsergetstarted.png)


Enter a phrase you want turned to speech in the input box, then choose **Synthesize**. When the audio is ready to play, a message appears. Use the audio player controls to hear the synthesized speech.

## Full Sample


Here is the full HTML page with the browser script. It's also available [here on GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code//browserstart/polly.html).

```
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>AWS SDK for JavaScript - Browser Getting Started Application</title>
  </head>

  <body>
    <div id="textToSynth">
      <input autofocus size="23" type="text" id="textEntry" value="It's very good to meet you."/>
      <button class="btn default" onClick="speakText()">Synthesize</button>
      <p id="result">Enter text above then click Synthesize</p>
    </div>
    <audio id="audioPlayback" controls>
      <source id="audioSource" type="audio/mp3" src="">
    </audio>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.410.0.min.js"></script>
    <script type="text/javascript">

        // Initialize the Amazon Cognito credentials provider
        AWS.config.region = 'REGION';
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId: 'IDENTITY_POOL_ID'});

        // Function invoked by button click
        function speakText() {
            // Create the JSON parameters for getSynthesizeSpeechUrl
            var speechParams = {
                OutputFormat: "mp3",
                SampleRate: "16000",
                Text: "",
                TextType: "text",
                VoiceId: "Matthew"
            };
            speechParams.Text = document.getElementById("textEntry").value;

            // Create the Polly service object and presigner object
            var polly = new AWS.Polly({apiVersion: '2016-06-10'});
            var signer = new AWS.Polly.Presigner(speechParams, polly)

            // Create presigned URL of synthesized speech file
            signer.getSynthesizeSpeechUrl(speechParams, function(error, url) {
            if (error) {
                document.getElementById('result').innerHTML = error;
            } else {
                document.getElementById('audioSource').src = url;
                document.getElementById('audioPlayback').load();
                document.getElementById('result').innerHTML = "Speech ready to play.";
            }
          });
        }
    </script>
  </body>
</html>
```

## Possible Enhancements


Here are variations on this application you can use to further explore using the SDK for JavaScript in a browser script.
+ Experiment with other sound output formats.
+ Add the option to select any of the various voices provided by Amazon Polly.
+ Integrate an identity provider like Facebook or Amazon to use with the authenticated IAM role.

# Getting Started in Node.js
New Getting Started in Node.js[this text is ignored](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-nodejs.html)

Getting Started in Node.js has been rewritten to use updated sample code and to provide greater detail in how to create the `package.json` file as well as the Node.js code itself. See [Getting Started in Node.js](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-nodejs.html) for the new content.

![\[JavaScript code example that applies to Node.js execution\]](http://docs.amazonaws.cn/en_us/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**This Node.js code example shows:**
+ How to create the `package.json` manifest for your project.
+ How to install and include the modules that your project uses.
+ How to create an Amazon Simple Storage Service (Amazon S3) service object from the `AWS.S3` client class.
+ How to create an Amazon S3 bucket and upload an object to that bucket.

## The Scenario


The example shows how to set up and run a simple Node.js module that creates an Amazon S3 bucket, then adds a text object to it. 

Because bucket names in Amazon S3 must be globally unique, this example includes a third-party Node.js module that generates a unique ID value that you can incorporate into the bucket name. This additional module is named `uuid`.

## Prerequisite Tasks


To set up and run this example, you must first complete these tasks:
+ Create a working directory for developing your Node.js module. Name this directory `awsnodesample`. Note that the directory must be created in a location that can be updated by applications. For example, in Windows, do not create the directory under "C:\$1Program Files".
+ Install Node.js. For more information, see the [Node.js website](https://nodejs.org). You can find downloads of the current and LTS versions of Node.js for a variety of operating systems at [https://nodejs.org/en/download/current/](https://nodejs.org/en/download/current/).

**Contents**
+ [

## The Scenario
](#getting-started-nodejs-scenario)
+ [

## Prerequisite Tasks
](#getting-started-nodejs-prerequisites)
+ [

## Step 1: Install the SDK and Dependencies
](#getting-started-nodejs-install-sdk)
+ [

## Step 2: Configure Your Credentials
](#getting-started-nodejs-credentials)
+ [

## Step 3: Create the Package JSON for the Project
](#getting-started-nodejs-download)
+ [

## Step 4: Write the Node.js Code
](#getting-started-nodejs-js-code)
+ [

## Step 5: Run the Sample
](#getting-started-nodejs-run-sample)

## Step 1: Install the SDK and Dependencies


You install the SDK for JavaScript package using [npm (the Node.js package manager)](https://www.npmjs.com). 

From the `awsnodesample` directory in the package, type the following at the command line.

```
npm install aws-sdk
```

This command installs the SDK for JavaScript in your project, and updates `package.json` to list the SDK as a project dependency. You can find information about this package by searching for "aws-sdk" on the [npm website](https://www.npmjs.com).

Next, install the `uuid` module to the project by typing the following at the command line, which installs the module and updates `package.json`. For more information about `uuid`, see the module's page at [https://www.npmjs.com/package/uuid](https://www.npmjs.com/package/uuid).

```
npm install uuid
```

These packages and their associated code are installed in the `node_modules` subdirectory of your project.

For more information on installing Node.js packages, see [Downloading and installing packages locally](https://docs.npmjs.com/getting-started/installing-npm-packages-locally) and [Creating Node.js Modules](https://docs.npmjs.com/getting-started/creating-node-modules) on the [npm (Node.js package manager) website](https://www.npmjs.com). For information about downloading and installing the Amazon SDK for JavaScript, see [Installing the SDK for JavaScript](installing-jssdk.md).

## Step 2: Configure Your Credentials


You need to provide credentials to Amazon so that only your account and its resources are accessed by the SDK. For more information about obtaining your account credentials, see [SDK authentication with Amazon](getting-your-credentials.md).

To hold this information, we recommend you create a shared credentials file. To learn how, see [Loading Credentials in Node.js from the Shared Credentials File](loading-node-credentials-shared.md). Your credentials file should resemble the following example.

```
[default]
aws_access_key_id = YOUR_ACCESS_KEY_ID
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
```

You can determine whether you have set your credentials correctly by executing the following code with Node.js:

```
var AWS = require("aws-sdk");

AWS.config.getCredentials(function(err) {
  if (err) console.log(err.stack);
  // credentials not loaded
  else {
    console.log("Access key:", AWS.config.credentials.accessKeyId);
  }
});
```

Similarly, if you have set your region correctly in your `config` file, you can display that value by setting the `AWS_SDK_LOAD_CONFIG` environment variable to any value and using the following code:

```
var AWS = require("aws-sdk");

console.log("Region: ", AWS.config.region);
```

## Step 3: Create the Package JSON for the Project


After you create the `awsnodesample` project directory, you create and add a `package.json` file for holding the metadata for your Node.js project. For details about using `package.json` in a Node.js project, see [Creating a package.json file](https://docs.npmjs.com/creating-a-package-json-file).

In the project directory, create a new file named `package.json`. Then add this JSON to the file.

```
{
  "dependencies": {},
  "name": "aws-nodejs-sample",
  "description": "A simple Node.js application illustrating usage of the SDK for JavaScript.",
  "version": "1.0.1",
  "main": "sample.js",
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "NAME",
  "license": "ISC"
}
```

Save the file. As you install the modules you need, the `dependencies` portion of the file will be completed. You can find a JSON file that shows an example of these dependencies [here on GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/nodegetstarted/example_package.json). 

## 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](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/nodegetstarted/sample.js).

## Step 5: Run the Sample


Type the following command to run the sample.

```
node sample.js
```

If the upload is successful, you'll see a confirmation message at the command line. You can also find the bucket and the uploaded text object in the [Amazon S3 console](https://console.amazonaws.cn/s3/).