Skip to content
| Marketplace
Sign in
Visual Studio Code>Snippets>node-aws-snippetsNew to Visual Studio Code? Get it now.
node-aws-snippets

node-aws-snippets

Teaverse

|
33 installs
| (0) | Free
A curated collection of Node.js and AWS code snippets to accelerate backend development.
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

☕ Teaverse Node.js + AWS Snippets

A professional and production-ready snippet collection for building Node.js applications using Express.js, AWS SDK, S3, DynamoDB, Multer, and EJS.
Designed to speed up development and reduce repetitive coding when building full-stack or backend applications integrated with AWS cloud services.


Instructions - Step 1

  1. npm init -y; npm i ejs nodemon express; npm install aws-sdk dotenv multer; npm install uuid
  2. Add "start": "nodemon index.js" to your package.json
  3. Create index.js in the root directory
  4. Create a .env with tea-env (remove spaces and edit table name)
  5. In index.js run snippets in order: tea-1 → tea-5, then tea-8 (edit PORT to ${PORT})
  6. Create index.ejs in views/index.ejs, add HTML:5 structure
  7. Inside the <body> tag, insert snippets tea-form-save and tea-form-delete
  8. Add tea-6 → tea-7 edit save and edit id delete

Instructions - Step 2 (Deploy)

  1. ssh -i "key.pem" ubuntu@54.251.186.201
  2. Upload LOCAL -> Ubuntu(delete node-modules): scp -i "folder\key.pem" -r "folder_code" ubuntu@54.251.186.201:/home/ubuntu/
  3. Install dependencies: cd /home/ubuntu/<Folder_Project> and npm install
  4. Run by PM2: pm2 start index.js
  5. sudo env PATH=PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u ubuntu --hp /home/ubuntu
  6. pm2 save

📦 Snippet Overview

Prefix Title Description
tea-1 Import-Libraries-1 Import core libraries (Express, AWS SDK, Multer, etc.)
tea-2 AWS-Configuration-2 Configure AWS SDK, S3, and DynamoDB
tea-3 Multer-Configuration-3 Setup Multer to handle image uploads with type filtering
tea-4 Express-App-Initialization Initialize Express app and setup EJS as the view engine
tea-5 Route-Render-Homepage-5 Route to render homepage using data from DynamoDB
tea-6 Route-Upload-Save-6 Route to upload image to S3 and save data to DynamoDB
tea-7 Route-Delete-7 Route to delete selected employees from DynamoDB
tea-8 Start-Server-8 Start the Express server
tea-form-save Form-Template-Tea-Form-Save HTML form template to add a new employee
tea-form-delete Form-Template-Tea-Form-Delete HTML form template to delete selected employees
tea-env Environment-Config-Tea-Env Sample .env file for AWS setup
tea-ec2-deploy Deploy Node.js App to EC2 Instructions to deploy your app to AWS EC2 using SSH + PM2

💡 Full Example Code

🔹 Import Libraries

const express = require('express');
const AWS = require('aws-sdk');
const path = require('path');
const multer = require('multer');
require('dotenv').config();
const { v4: uuidv4 } = require('uuid');

🔹 AWS Configuration

AWS.config.update({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: process.env.AWS_REGION
});

const s3 = new AWS.S3();
const dynamo = new AWS.DynamoDB.DocumentClient();
const bucketName = process.env.AWS_S3_BUCKET_NAME;
const tableName = process.env.DYNAMO_TABLE_NAME;

🔹 Multer Configuration

const storage = multer.memoryStorage();

function checkFileType(file, cb) {
  const fileTypes = /jpeg|jpg|png|gif/;
  const extname = fileTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = fileTypes.test(file.mimetype);
  if (extname && mimetype) return cb(null, true);
  cb('Error: Images Only');
}

const upload = multer({
  storage,
  limits: { fileSize: 2 * 1024 * 1024 },
  fileFilter(req, file, cb) {
    checkFileType(file, cb);
  }
});

🔹 Express App Initialization

const app = express();
const PORT = 3000;

app.use(express.json({ extended: false }));
app.use(express.static('/views'));

app.set('view engine', 'ejs');
app.set('views', './views');

🔹 Route: Render Homepage

app.get('/', async (req, res) => {
  try {
    const params = { TableName: tableName };
    const data = await dynamo.scan(params).promise();
    res.render("index.ejs", { data: data.Items });
  } catch (error) {
    console.log(error);
    res.status(500).send("Lỗi server");
  }
});

🔹 Route: Save Employee + Upload Image to S3

app.post('/save', upload.single('hinhanh'), async (req, res) => {
  try {
    const manhansu = Number(req.body.manhansu);
    const hoten = req.body.hoten;
    const namsinh = Number(req.body.namsinh);
    const phongban = req.body.phongban;

    const hinhanh = req.file?.originalname.split('.');
    const fileType = hinhanh[hinhanh.length - 1];
    const filePath = `${manhansu}_${Date.now().toString()}.${fileType}`;

    const paramsS3 = {
      Bucket: bucketName,
      Key: filePath,
      Body: req.file.buffer,
      ContentType: req.file.mimetype
    };

    s3.upload(paramsS3, async (error, data) => {
      if (error) {
        console.log(error);
        return res.status(500).send("Lỗi Server");
      }

      const paramsDynamo = {
        TableName: tableName,
        Item: { manhansu, hoten, namsinh, phongban, hinhanh: data.Location }
      };

      await dynamo.put(paramsDynamo).promise();
      return res.redirect("/");
    });

    console.log(filePath);
  } catch (error) {
    console.log(error);
    res.status(500).send("Lỗi server");
  }
});

🔹 Route: Delete Selected Employees

app.post('/delete', upload.fields([]), (req, res) => {
  const selectedbox = Object.keys(req.body);

  if (!selectedbox || selectedbox.length <= 0) {
    return res.redirect('/');
  }

  try {
    function onDeleteItem(length) {
      const params = {
        TableName: tableName,
        Key: { manhansu: Number(selectedbox[length]) },
      };

      dynamo.delete(params, (err) => {
        if (err) {
          console.error('Lỗi xoá dữ liệu: ', err);
          return res.status(500).json({ message: 'Internal Server Error' });
        } else {
          if (length > 0) {
            onDeleteItem(length - 1);
          } else {
            return res.redirect('/');
          }
        }
      });
    }

    onDeleteItem(selectedbox.length - 1);
  } catch (error) {
    console.error('Lỗi server: ', error);
    return res.status(500).json({ message: 'Internal Server Error' });
  }
});

🔹 Start Server

app.listen(PORT, () => {
  console.log(`Server đang chạy tại PORT: ${PORT}`);
});

🔹 .env Configuration

AWS_REGION=ap-southeast-1
AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY
AWS_SECRET_ACCESS_KEY=YOUR_SECRET_KEY
DYNAMO_TABLE_NAME=nhansu1
AWS_S3_BUCKET_NAME=bucketnguyenquan

🔹 Deploy to EC2 (PM2)

# SSH vào EC2
ssh -i "your-key.pem" ubuntu@<PUBLIC_IPV4_EC2>

# Cập nhật hệ thống
sudo apt update && sudo apt upgrade -y

# Cài Node.js 18
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs

# Cài PM2
sudo npm install -g pm2

# Upload code (xóa node_modules trước)
scp -i "your-key.pem" -r "your-project" ubuntu@<PUBLIC_IPV4_EC2>:/home/ubuntu/

# Vào thư mục & cài dependencies
cd /home/ubuntu/your-project
npm install

# Chạy bằng PM2
pm2 start index.js
sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u ubuntu --hp /home/ubuntu
pm2 save

# Kiểm tra
pm2 list
  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2025 Microsoft