본문 바로가기
반응형

Node js53

Node JS - dayjs로 날짜, 시간 관리하기 Node JS 전체 링크 참고 - 두 날짜 사이의 시간 차이 구하기 dayjs를 이용하면 날짜나 시간과 관련된 처리를 쉽게할 수 있다. npm install dayjs 예시 코드는 다음과 같다. const dayjs = require("dayjs"); // 현재 시간 가져오기 const now = dayjs(); console.log("현재 시간 : ", now.format()); console.log("포맷 변경 : ", now.format("YY-MM-DD / HH:mm:ss")); console.log("연도 확인 : ", now.get("year")); // or y console.log("시간 변경 : ", now.set("hour", 0).format()); // or h // -> year/.. 2024. 2. 22.
Node JS - 폴더 내부의 전체 파일 개수 구하기 (Counting the Total Number of Files In Folder) Node JS 전체 링크 지정한 경로에 대해 파일의 개수를 구하려면 fs와 path 모듈을 이용하면 된다. 폴더 내부에 폴더가 있다면 재귀적으로 함수를 호출해서 파일 개수를 누적한다. const fs = require("fs"); const path = require("path"); const countFilesInDirectory = (dir) => { let count = 0; const items = fs.readdirSync(dir); for (const item of items) { const itemPath = path.join(dir, item); const stats = fs.statSync(itemPath); if (stats.isDirectory()) { count += countFil.. 2024. 2. 8.
깃허브 액션 - 로또 번호 수집해서 json으로 저장하기 (리포지토리 파일 수정하기) Node JS 전체 링크 Git / GitHub 전체 링크 참고 - Schedule로 반복 작업하기 - RESTful API로 파일 쓰기 깃허브 액션으로 로또 번호를 수집해서 깃허브 리포지토리에 저장해 보자. 참고로 1103회 로또 번호는 다음과 같다. 로또 번호 API 사용하기 동행복권에서는 회차별 로또 번호에 대한 정보를 주는 API를 제공한다. drwNo에 숫자를 넣으면 해당 회차별 번호를 알 수 있다. https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=${drwNo} Node JS에서 아래 코드를 실행해 보자. const axios = require("axios"); const getLottoNumber = async (drwNo.. 2024. 1. 23.
Node JS - multer로 이미지 업로드하기 (Upload Images with multer) Node JS 전체 링크 참고 - FormData와 multer로 여러 파일 업로드하기- 깃허브 API로 이미지 업로드하기- 캡처한 이미지 여러 개 업로드하기 프론트엔드(리액트)에서 이미지를 업로드한 후, 서버(Node JS)에 저장해 보자. 먼저 링크를 참고하여 ReactImageList.js를 아래와 같이 수정하자.불필요한 내용은 지우고 서버에 업로드만 하는 메서드인 serverUpload만 구현한다.import React, { useEffect, useState } from "react";import Box from "@mui/material/Box";// upload buttonimport { styled } from "@mui/material/styles";impo.. 2024. 1. 22.
Node JS - exec으로 Git Push 하기 Node JS 전체 링크 Git / GitHub 전체 링크 원격 저장소에 변경된 내용을 주기적으로 Push를 하거나, 리액트 등에서 특정 이벤트가 발생했을 때 Push를 한다고 가정해 보자. 먼저 필요한 명령어를 shell script로 만들어 둔다. (test.sh) #!/bin/bash # shell script가 있는 디렉토리 이동 cd "D:/github/auto-test" # Git 저장소 초기화 git init # 원격 저장소의 main 브랜치 fetch git fetch origin main # 로컬 저장소의 main 브랜치로 원격 저장소의 main 브랜치 병합 git merge origin/main # 변경된 모든 파일을 스테이징 git add . # 커밋 생성 git commit -m ".. 2024. 1. 14.
Node JS - PM2 ecosystem.config.js로 환경 변수 설정하기 Node JS 전체 링크 참고 - 인증 토큰 획득 서버 구현하기 pm2로 프로세스를 관리할 때, dotenv로 환경 변수를 적용하더라도 잘 반영되지 않는 경우가 있다. pm2의 ecosystem을 이용해서 환경 변수를 설정해 보자. pm2를 전역으로 설치한다. npm install pm2 -g 정상적으로 설치가 되었다면 version을 확인해 보자. $ pm2 -version 5.3.0 pm2 start [Node App 진입점](여기서는 server.js) 으로 백그라운드로 App을 실행할 수 있다. $ pm2 start server.js [PM2] Starting D:\github\node-server\server.js in fork_mode (1 instance) [PM2] Done. ┌────┬─.. 2023. 12. 25.
Node JS - Express 중첩 라우팅 설정하기 (Setting Nested Routing) Node JS 전체 링크 Express에서 중첩 라우팅을 설정해보자. server.js에 router_test를 추가한다. const express = require("express"); const app = express(); const cors = require("cors"); app.use(cors()); const router_test = require("./routes/router_test"); app.use("/router_test", router_test); app.listen(3002, () => { console.log("Node.js Server is running on port 3002..."); }); router_test.js는 다음과 같다. const express = requi.. 2023. 12. 23.
리액트 - Toast UI Editor로 메일 보내기 with nodemailer 리액트 전체 링크 Node JS 전체 링크 참고 - body-parser를 이용해 데이터 전송 받기 - Toast UI 에디터로 깃허브 마크다운 저장하기 - nodemailer로 구글, 네이버, 다음 카카오 메일 보내기 nodemailer의 html 설정으로 어느 정도 형식이 있는 메일을 보낼 수 있다. 리액트에서 Toast UI Editor를 이용하면 getHTML() 으로 html 태그를 쉽게 얻을 수 있다. 먼저 링크를 참고하여 express로 nodemailer 라우터를 구축하자. ./routes/post_man.js 메일이 전송되지 않은 경우 try catch를 이용해 false를 send하도록 하였다. const express = require("express"); const router = .. 2023. 12. 10.
Node JS - body-parser를 이용해 데이터 전송 받기 (POST with body-parser) Node JS 전체 링크 참고 - POST로 데이터 전송 받기 Body Parser를 이용해서 데이터를 받아보자. npm install body-parser ./routes/axios_post_test.js를 아래와 같이 만들자. body parser를 쓰더라도 query를 사용할 수 있다. const express = require("express"); const router = express.Router(); const bodyParser = require("body-parser"); router.use(bodyParser.json({ limit: 100000000 })); // 100MB router.post("/", (req, res) => { let name = req.query.name; le.. 2023. 12. 9.
반응형