

 O [Guia de referência da API do AWS SDK para JavaScript V3](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/) descreve em detalhes todas as operações da API para o AWS SDK para JavaScript versão 3 (V3). 

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Conceitos básicos sobre o Node.js
<a name="getting-started-nodejs"></a>

Este guia mostra como inicializar um pacote NPM, adicionar um cliente de serviço ao seu pacote e usar o JavaScript SDK para chamar uma ação de serviço.

## O cenário
<a name="getting-started-nodejs-scenario"></a>

**Crie um novo pacote NPM com um arquivo principal que faz o seguinte:**
+ Cria um bucket do Amazon Simple Storage Service
+ Coloca um objeto no bucket do Amazon S3
+ Lê o objeto no bucket do Amazon S3
+ Confirma se o usuário deseja excluir recursos

## Pré-requisitos
<a name="getting-started-nodejs-prerequisites"></a>

Antes de executar o exemplo, faça o seguinte:
+ Configure a autenticação do SDK. Para obter mais informações, consulte [Autenticação do SDK com AWS](getting-your-credentials.md).
+ Instale [o Node.js](https://nodejs.org/en/download). AWS recomenda usar a versão Active LTS do Node.js para desenvolvimento.

## Etapa 1: configurar a estrutura do pacote e instalar pacotes do cliente
<a name="getting-started-nodejs-setup-structure"></a>

Para configurar a estrutura do pacote e instalar pacotes do cliente:

1. Crie uma nova pasta `nodegetstarted` para conter o pacote.

1. Na linha de comando, navegue até a nova pasta.

1. Execute o seguinte comando para criar um arquivo `package.json` padrão:

   ```
   npm init -y
   ```

1. Execute o comando a seguir para instalar o pacote de cliente do Amazon S3:

   ```
   npm i @aws-sdk/client-s3
   ```

1. Adicione `"type": "module"` ao arquivo `package.json`. Isso faz com que o Node.js use a sintaxe moderna do ESM. O arquivo `package.json` final deverá ser semelhante ao seguinte:

   ```
   {
     "name": "example-javascriptv3-get-started-node",
     "version": "1.0.0",
     "description": "This guide shows you how to initialize an NPM package, add a service client to your package, and use the JavaScript SDK to call a service action.",
     "main": "index.js",
     "scripts": {
   "test": "vitest run **/*.unit.test.js"
     },
     "author": "Your Name",
     "license": "Apache-2.0",
     "dependencies": {
    "@aws-sdk/client-s3": "^3.420.0"
     },
     "type": "module"
   }
   ```

## Etapa 2: Adicionar as importações e o código SDK necessários
<a name="getting-started-with-node-js-add-code"></a>

Adicione o código a seguir a um arquivo denominado `index.js` na pasta `nodegetstarted`.

```
// This is used for getting user input.
import { createInterface } from "node:readline/promises";

import {
  S3Client,
  PutObjectCommand,
  CreateBucketCommand,
  DeleteObjectCommand,
  DeleteBucketCommand,
  paginateListObjectsV2,
  GetObjectCommand,
} from "@aws-sdk/client-s3";

export async function main() {
  // A region and credentials can be declared explicitly. For example
  // `new S3Client({ region: 'us-east-1', credentials: {...} })` would
  //initialize the client with those settings. However, the SDK will
  // use your local configuration and credentials if those properties
  // are not defined here.
  const s3Client = new S3Client({});

  // Create an Amazon S3 bucket. The epoch timestamp is appended
  // to the name to make it unique.
  const bucketName = `test-bucket-${Date.now()}`;
  await s3Client.send(
    new CreateBucketCommand({
      Bucket: bucketName,
    }),
  );

  // Put an object into an Amazon S3 bucket.
  await s3Client.send(
    new PutObjectCommand({
      Bucket: bucketName,
      Key: "my-first-object.txt",
      Body: "Hello JavaScript SDK!",
    }),
  );

  // Read the object.
  const { Body } = await s3Client.send(
    new GetObjectCommand({
      Bucket: bucketName,
      Key: "my-first-object.txt",
    }),
  );

  console.log(await Body.transformToString());

  // Confirm resource deletion.
  const prompt = createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  const result = await prompt.question("Empty and delete bucket? (y/n) ");
  prompt.close();

  if (result === "y") {
    // Create an async iterator over lists of objects in a bucket.
    const paginator = paginateListObjectsV2(
      { client: s3Client },
      { Bucket: bucketName },
    );
    for await (const page of paginator) {
      const objects = page.Contents;
      if (objects) {
        // For every object in each page, delete it.
        for (const object of objects) {
          await s3Client.send(
            new DeleteObjectCommand({ Bucket: bucketName, Key: object.Key }),
          );
        }
      }
    }

    // Once all the objects are gone, the bucket can be deleted.
    await s3Client.send(new DeleteBucketCommand({ Bucket: bucketName }));
  }
}

// Call a function if this file was run directly. This allows the file
// to be runnable without running on import.
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```

O código de exemplo pode ser encontrado [aqui em GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/nodegetstarted/index.js).

## Etapa 3: Executar o exemplo
<a name="getting-started-with-node-js-run"></a>

**nota**  
Lembre-se de fazer login\$1 Se você estiver usando o IAM Identity Center para se autenticar, lembre-se de fazer login usando o AWS CLI `aws sso login` comando.

1. Executar `node index.js`.

1. Escolha se deseja esvaziar e excluir o bucket.

1. Se você não excluir o bucket, certifique-se de esvaziá-lo manualmente e excluí-lo mais tarde.