Inizia con Node.js - AWS SDK for JavaScript

La Guida di riferimento dell'API AWS SDK for JavaScript V3 descrive in dettaglio tutte le operazioni API per la AWS SDK for JavaScript versione 3 (V3).

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Inizia con Node.js

Questa guida mostra come inizializzare un pacchetto NPM, aggiungere un client di servizio al pacchetto e utilizzare l' JavaScript SDK per avviare un'azione di servizio.

Lo scenario

Crea un nuovo pacchetto NPM con un file principale che esegua le seguenti operazioni:
  • Crea un bucket Amazon Simple Storage Service

  • Inserisce un oggetto nel bucket Amazon S3

  • Legge l'oggetto nel bucket Amazon S3

  • Conferma se l'utente desidera eliminare le risorse

Prerequisiti

Prima di eseguire l'esempio, è necessario effettuare le seguenti operazioni:

Fase 1: Configurare la struttura dei pacchetti e installare i pacchetti client

Per configurare la struttura dei pacchetti e installare i pacchetti client:

  1. Crea una nuova cartella nodegetstarted per contenere il pacchetto.

  2. Dalla riga di comando, accedi alla nuova cartella.

  3. Esegui il comando seguente per creare un package.json file predefinito:

    npm init -y
  4. Esegui il seguente comando per installare il pacchetto client Amazon S3:

    npm i @aws-sdk/client-s3
  5. Aggiungi "type": "module" al package.json file. Ciò indica a Node.js di utilizzare la moderna sintassi ESM. La versione finale package.json dovrebbe essere simile alla seguente:

    { "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" }

Passaggio 2: aggiungi le importazioni e il codice SDK necessari

Aggiungi il codice seguente a un file denominato index.js nella nodegetstarted cartella.

// This is used for getting user input. import { createInterface } from "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 "url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); }

Il codice di esempio può essere trovato qui GitHub.

Fase 3: Esegui l'esempio

Nota

Ricordati di effettuare l'accesso! Se utilizzi IAM Identity Center per l'autenticazione, ricordati di accedere utilizzando il AWS CLI aws sso login comando.

  1. Esegui node index.js.

  2. Scegli se svuotare ed eliminare il bucket.

  3. Se non elimini il bucket, assicurati di svuotarlo manualmente ed eliminarlo in un secondo momento.