Commencez avec Node.js - AWS SDK for JavaScript

Le guide de référence de l'API AWS SDK for JavaScript V3 décrit en détail toutes les opérations de l'API pour la AWS SDK for JavaScript version 3 (V3).

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Commencez avec Node.js

Ce guide explique comment initialiser un package NPM, ajouter un client de service à votre package et utiliser le JavaScript SDK pour appeler une action de service.

Le scénario

Créez un nouveau package NPM avec un fichier principal qui effectue les opérations suivantes :
  • Crée un bucket Amazon Simple Storage Service

  • Place un objet dans le compartiment Amazon S3

  • Lit l'objet dans le compartiment Amazon S3

  • Confirme si l'utilisateur souhaite supprimer des ressources

Prérequis

Avant de pouvoir exécuter cet exemple, vous devez effectuer les opérations suivantes :

Étape 1 : Configuration de la structure des packages et installation des packages clients

Pour configurer la structure des packages et installer les packages clients :

  1. Créez un nouveau dossier nodegetstarted pour contenir le package.

  2. À partir de la ligne de commande, accédez au nouveau dossier.

  3. Exécutez la commande suivante pour créer un package.json fichier par défaut :

    npm init -y
  4. Exécutez la commande suivante pour installer le package client Amazon S3 :

    npm i @aws-sdk/client-s3
  5. Ajoutez "type": "module" au package.json fichier. Cela indique à Node.js d'utiliser la syntaxe ESM moderne. La finale package.json devrait ressembler à ce qui suit :

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

Étape 2 : ajouter les importations et le code SDK nécessaires

Ajoutez le code suivant à un fichier nommé index.js dans le nodegetstarted dossier.

// 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(); }

L'exemple de code se trouve ici GitHub.

Étape 3 : Exécutez l'exemple

Note

N'oubliez pas de vous connecter ! Si vous utilisez IAM Identity Center pour vous authentifier, n'oubliez pas de vous connecter à l'aide de la AWS CLI aws sso login commande.

  1. Exécutez node index.js.

  2. Choisissez de vider et de supprimer le compartiment.

  3. Si vous ne supprimez pas le compartiment, veillez à le vider manuellement et à le supprimer ultérieurement.