w3resource

Node.js AWS integration: S3, Lambda, and DynamoDB Examples


Integrating AWS with Node.js

Amazon Web Services (AWS) provides cloud-based solutions like storage, computing, and databases. Node.js can be seamlessly integrated with AWS to leverage services such as S3 (storage), Lambda (serverless functions), and DynamoDB (NoSQL database). This guide covers how to set up AWS SDK in Node.js, perform basic operations, and provides practical examples.


Syntax:

    1. Install the AWS SDK:

    npm install aws-sdk
    

    2. Import and configure the SDK in your Node.js application.

    3. Use AWS services by creating service-specific objects, such as S3 for storage.


Examples and Code

1. Installation and Setup

Install the AWS SDK for Node.js:

Code:

npm install aws-sdk

2. Configure AWS SDK

Example Code:

Code:

// Import AWS SDK
const AWS = require('aws-sdk');

// Configure AWS with your credentials and region
AWS.config.update({
    accessKeyId: 'your-access-key-id',        // Replace with your AWS Access Key
    secretAccessKey: 'your-secret-access-key', // Replace with your AWS Secret Key
    region: 'us-east-1',                      // Specify the region
});

Explanation:

  • AWS.config.update(): Configures the AWS SDK with access keys and region.
  • Use environment variables or IAM roles for better security instead of hardcoding credentials.

3. Using AWS S3 for File Operations

Uploading a File to S3:

Code:

// Import file system module
const fs = require('fs');

// Create an S3 service object
const s3 = new AWS.S3();

// Define upload parameters
const uploadParams = {
    Bucket: 'your-bucket-name',             // Replace with your S3 bucket name
    Key: 'example.txt',                     // File name in the bucket
    Body: fs.createReadStream('example.txt'), // Local file to upload
};

// Upload the file
s3.upload(uploadParams, (err, data) => {
    if (err) {
        console.error('Error uploading file:', err);
    } else {
        console.log('File uploaded successfully:', data.Location);
    }
});

Downloading a File from S3:

Code:

// Define download parameters
const downloadParams = {
    Bucket: 'your-bucket-name', // Replace with your S3 bucket name
    Key: 'example.txt',         // File name to download
};

// Download the file
s3.getObject(downloadParams, (err, data) => {
    if (err) {
        console.error('Error downloading file:', err);
    } else {
        console.log('File content:', data.Body.toString()); // Display file content
    }
});

Explanation:

  • s3.upload(): Uploads a file to S3.
  • s3.getObject(): Retrieves a file from S3.

4. Using AWS Lambda with Node.js

Invoking a Lambda Function:

Code:

// Create a Lambda service object
const lambda = new AWS.Lambda();

// Define parameters to invoke the function
const params = {
    FunctionName: 'my-lambda-function', // Replace with your Lambda function name
    Payload: JSON.stringify({ key: 'value' }), // Input data for the function
};

// Invoke the Lambda function
lambda.invoke(params, (err, data) => {
    if (err) {
        console.error('Error invoking Lambda:', err);
    } else {
        console.log('Lambda response:', JSON.parse(data.Payload));
    }
});

Explanation:

  • lambda.invoke(): Executes a serverless Lambda function.
  • Pass input data as a JSON payload.

5. Using DynamoDB for Database Operations

Inserting Data into DynamoDB:

Code:

// Create a DynamoDB DocumentClient
const dynamoDB = new AWS.DynamoDB.DocumentClient();

// Define parameters for the item
const params = {
    TableName: 'your-table-name', // Replace with your table name
    Item: {
        id: '123',               // Primary key
        name: 'Example Item',    // Data attributes
        info: 'Some additional info',
    },
};

// Insert the item
dynamoDB.put(params, (err, data) => {
    if (err) {
        console.error('Error inserting item:', err);
    } else {
        console.log('Item inserted successfully:', data);
    }
});

Querying Data from DynamoDB:

Code:

// Define parameters to query the table
const queryParams = {
    TableName: 'your-table-name', // Replace with your table name
    KeyConditionExpression: 'id = :id', // Query condition
    ExpressionAttributeValues: {
        ':id': '123', // Replace with the key value to query
    },
};

// Query the table
dynamoDB.query(queryParams, (err, data) => {
    if (err) {
        console.error('Error querying table:', err);
    } else {
        console.log('Query result:', data.Items);
    }
});

Best Practices for Using AWS with Node.js

    1. Avoid Hardcoding Credentials: Use environment variables or IAM roles for better security.

    2. Enable SDK Logging: Use AWS.config.logger for debugging API requests.

    3. Use S3 Presigned URLs: Generate URLs for temporary access to S3 objects.

    4. Retry and Throttle: Implement retries for transient errors, especially for Lambda and DynamoDB.

    5. Optimize for Region: Always choose the closest region to minimize latency.


Common AWS Services for Node.js

Service Purpose
S3 Object storage for files and backups.
Lambda Serverless computing for event-driven applications.
DynamoDB NoSQL database for scalable storage.
EC2 Virtual servers for web applications.
CloudWatch Monitoring and logging AWS resources.

Practical Guides to Node.js Snippets and Examples.



Follow us on Facebook and Twitter for latest update.