La Guía de referencia de la API de AWS SDK for JavaScript V3 describe en detalle todas las operaciones de la API para la versión 3 (V3) de AWS SDK for JavaScript.
Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.
Introducción a Node.js
Esta guía le muestra cómo inicializar un paquete de NPM, agregar un cliente de servicio a su paquete y usar el JavaScript SDK para realizar una acción de servicio.
El escenario
Cree un nuevo paquete de NPM con un archivo principal que haga lo siguiente:
- Crea un bucket de Amazon Simple Storage Service 
- Coloca un objeto en el bucket de Amazon S3 
- Lee el objeto en el bucket de Amazon S3 
- Confirma si el usuario quiere eliminar los recursos 
Requisitos previos
Para poder ejecutar el ejemplo, debe hacer lo siguiente:
- 
        Configura la autenticación del SDK. Para obtener más información, consulte Autenticación del SDK con AWS. 
- 
                Instale Node.js. AWS recomienda utilizar la versión Active LTS de Node.js para el desarrollo. 
Paso 1: Configurar la estructura de paquetes e instalar los paquetes de cliente
Para configurar la estructura de paquetes e instalar los paquetes de clientes:
- Cree una nueva carpeta - nodegetstartedpara meter el paquete.
- Desde la línea de comandos, navegue hasta la nueva carpeta. 
- Ejecute el siguiente comando para crear un archivo - package.jsonpredeterminado:- npm init -y
- Para instalar el paquete de cliente de AMazon S3, ejecute el comando siguiente: - npm i @aws-sdk/client-s3
- 
            Añada "type": "module"al archivopackage.json. Esto le indica a Node.js que utilice la sintaxis ESM moderna. Elpackage.jsonfinal debe ser similar al siguiente:{ "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" }
Paso 2: Agregar las importaciones y el código de SDK necesarios
Agregue el siguiente código a un archivo llamado index.js en la carpeta 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(); }
El código de ejemplo se puede encontrar aquí en  GitHub
Paso 3: Ejecutar el ejemplo
nota
¡Recuerde iniciar sesión! Si utiliza el Centro de identidad de IAM para autenticarse, no olvide iniciar sesión con el AWS CLI aws sso login comando.
- Ejecute - node index.js.
- Indique si quiere vaciar y eliminar el bucket. 
- Si no elimina el bucket, asegúrese de vaciarlo manualmente y eliminarlo más adelante.