node.js로 DynamoDB에 json 데이터 넣기
AWS
안에 DynamoDB
안에 여러개의 json
파일을 한꺼번에 넣어야하는 경우가 있다.
node.js
와 AWS package
그리고 AWS IAM
에서 발급해주는 key
값을 이용해서 넣는 코드이다.
#1. 먼저 aws-sdk
module을 설치
https://www.npmjs.com/package/aws-sdk
aws-sdk
AWS SDK for JavaScript
www.npmjs.com
npm install aws-sdk
#2. 그 다음 AWS
정보가 담겨있는 config
파일을 하나 만든다.
module.exports = { aws_table_name: "table_name", aws_local_config: { region: "your_region", endpoint: "endpoint" }, aws_remote_config: { accessKeyId: "your_id", secretAccessKey: "your_key", region: "your_region" } }
위의 accessKeyId
와 secretAccessKey
는 AWS IAM
에서 발급이 가능하다.
또한 region
과 endpoint
또한 자신의 region
에 맞게 넣어주면 된다.
(검색 해보면 자세히 나와있다.)
https://aws.amazon.com/ko/premiumsupport/knowledge-center/create-access-key/
AWS 액세스 키 생성
프로그램, 스크립트 또는 개발자가 사용자의 AWS 계정에 있는 리소스에 프로그램 방식으로 액세스하도록 허용하려면 AWS 액세스 키가 있어야 합니다. 새 액세스 키를 생성하려면 어떻게 해야 하
aws.amazon.com

#3. 그다음 아래와 같이 js file
생성
const AWS = require("aws-sdk"); const fs = require("fs"); const config = require('./config/config.js'); const fileName = require('./fileName'); AWS.config.update(config.aws_remote_config); let docClient = new AWS.DynamoDB.DocumentClient(); console.log("Connect DynamoDB"); fileName.forEach((fileName, idx) => { setTimeout(() => { console.log(fileName, idx); insertFileNameJson(fileName); }, 3000 * idx); }); const insertFileNameJson = (fileName) => { let insertData = []; fs.stat(`${fileName}.json`, (err, stats) =>{ if (err.code === "ENOENT") { console.log("File is not exist"); } else { insertData.push(JSON.parse(fs.readFileSync(`${fileName}.json`, "utf8"))); insertData.forEach((data) => { let params = { TableName: "table_name", Item: { uuid: uuid, name: name, ... your_data } }; docClient.put(params, function(err, category) { if (err) { console.log("Failed", JSON.stringify(err, null, 2)); } else { console.log("Succeed"); } }); }); } }); }
fs module
도 사용했다.
https://nodejs.org/api/fs.html
File system | Node.js v16.11.0 Documentation
nodejs.org
aws-sdk
module과 접속정보를 통해서 AWS DynamoDB
와 연결후에
넣을 목록과 데이터(json file)을 준비하고
넣을 목록에 있는 파일명을 기준으로 map
함수를 통해서 돌아가면서 insert
하는 방식이다.
'Node & AWS > AWS' 카테고리의 다른 글
AWS EC2에 node.js 설치하기 (0) | 2022.10.03 |
---|---|
AWS Identity and Access Management (IAM) IAM #1 (0) | 2022.01.23 |
AWS Identity and Access Management (IAM) IAM #0 (0) | 2021.12.30 |
댓글
이 글 공유하기
다른 글
-
AWS EC2에 node.js 설치하기
AWS EC2에 node.js 설치하기
2022.10.03 -
AWS Identity and Access Management (IAM) IAM #1
AWS Identity and Access Management (IAM) IAM #1
2022.01.23 -
AWS Identity and Access Management (IAM) IAM #0
AWS Identity and Access Management (IAM) IAM #0
2021.12.30
댓글을 사용할 수 없습니다.