본문 바로가기
반응형

개발/Node JS34

Node JS - FormData와 multer로 여러 파일 업로드하기 (Upload Multiple Files with FormData and multer) Node JS 전체 링크 참고- multer로 이미지 업로드하기 다음과 같이 웹에서 여러 파일을 업로드하면 서버로 전송되도록 구현해 보자.리액트 input 태그에 multiple을 설정하면 여러 파일을 선택할 수 있다. handleUpload 구현은 전체 코드를 참고하자.formData의 append를 이용해 e.target.files를 순회하면서 파일을 추가한다.한글 파일이 있는 경우 파일 이름을 처리하기 위해 encodeURIComponent를 이용해야 한다.formData와 config("content-type": "multipart/form-data")를 post에 설정하여 서버로 전송하면 된다.import React from "react";import axios .. 2024. 4. 27.
Node JS - archiver로 폴더 압축해서 전송하기 (Compressing and Sending a Directory with Archiver) Node JS 전체 링크 참고 - https://www.npmjs.com/package/archiver 다음과 같은 경로가 있다고 가정하자. let folderPath = "D:\\github\\node-server\\macro\\myfiles"; // 압축할 폴더 경로 해당 경로에는 아래의 폴더와 파일이 존재한다. 리액트에서 버튼을 클릭하면 위의 폴더를 zip으로 다운로드 받아보자. 리액트 예시 코드는 다음과 같다. import React from "react"; import axios from "axios"; const DownloadZip = () => { const handleDownload = async () => { let server = `http://192.168.55.120:3002/fi.. 2024. 4. 15.
Node JS - Express, Socket.IO 서버 HTTPS 설정하기 (Setting up Express / Socket.IO Server with HTTPS) Node JS 전체 링크 Node JS의 Express에서 HTTPS 적용 예시는 다음과 같다. const fs = require("fs"); const https = require("https"); const cors = require("cors"); const app = express(); // express cors 설정 app.use(cors()); // 라우터 설정 // app.use("/router", router); // HTTPS Options const options = { key : fs.readdirSync("Your Key Path"), cert : fs.readdirSync("Your Certificate Path"), requestCert : false, // 클라이언트로부터 인.. 2024. 4. 3.
Node JS - Chonky 파일 맵 만들기 (Make Chonky File Map) 리액트 전체 링크 Node JS 전체 링크 참고 - 파일 브라우저 만들기 - chonky 기본 설정 확인하기 - 액션 추가하고 다크 모드 구현하기 - 커스텀 액션 추가하기 - Chonky 파일 맵 만들기 - 리포지토리의 폴더 정보 저장하기 - 깃허브 리포지토리를 파일 브라우저로 불러오기 - useNavigate로 Toast UI Editor 이동하기 Chonky 브라우저에서 사용하는 예시 demo.json은 다음과 같다. 1) 최상위 폴더의 ID인 rootFolderId가 필요하다. 2) fileMap에서 전체 폴더/파일에 대한 정보가 있다. 3) 폴더의 경우, isDir과 childrenIds, childrenCount 정보가 있다. 4) 파일의 경우, size와 isHidden 정보가 있다. 5) 폴.. 2024. 3. 16.
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.
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.
반응형