본문 바로가기
TIL/디지털트윈

05.22 디지털 트윈 부트캠프 27일차

by saramnim 2023. 5. 22.
728x90
백엔드

markdown preview enhanced

확장파일 설치 시, ctrl + shift + v를 누르면 깃허브 리드미처럼 정돈된 상태로 보인다.

 

nvm노드를 가상으로 설치하는 것?https://github.com/coreybutler/nvm-windows/releases

 

Releases · coreybutler/nvm-windows

A node.js version management utility for Windows. Ironically written in Go. - coreybutler/nvm-windows

github.com

window는 nvm-setup.exe 다운

exe 실행 후 설치 시 경로에 한글이 들어가면 제대로 설치되지 않을 수 있으니 조심하자!

nvm install 받고자 하는 버전

nvm install을 사용하면 내가 받고자 하는 node.js의 버전을 원하는대로 설치할 수 있다.

nvm use 받고자 하는 버전

npm use는 git branch처럼 내가 사용하고자 하는 버전을 선택해주는 명령어이다.

nvm list

nvm list로 내 컴퓨터에 가상으로 설치된 node를 확인할 수 있다.

 

npm install express-generator -g

express를 전역으로 설치해주자~!

 

express --ejs nodeproj

nodeproj 프로젝트를 생성해준다.

이때 프로젝트 생성이 되지 않고 오류가 발생하면

npx express --ejs nodeproj

위처럼 express 앞에 npx를 적어주면 된다.

 

npm install nodemon -g

nodemon 설치~!

 

package.json에서

다음과 같이 "dev" : "nodemon ./bin/www"를 작성해준 뒤

터미널에 npm run dev를 입력하면 

 

npm install -g eslint

eslint는 협업 시 통일성을 주는 도구로 초기 세팅이 필요하다.

eslint --init

eslint 초기 설정을 해주는 명령어로 다음과 같은 결과가 나온다.

You can also run this command directly using 'npm init @eslint/config'.
npx: 41개의 패키지를 3.109초만에 설치했습니다.
√ How would you like to use ESLint? · style       
√ What type of modules does your project use? · commonjs
√ Which framework does your project use? · none
√ Does your project use TypeScript? · No / Yes
√ Where does your code run? · browser
√ How would you like to define a style for your project? · guide
√ Which style guide do you want to follow? · airbnb      
√ What format do you want your config file to be in? · JSON  
Checking peerDependencies of eslint-config-airbnb-base@latest
Local ESLint installation not found.
The config that you've selected requires the following dependencies:

eslint-config-airbnb-base@latest eslint@^7.32.0 || ^8.2.0 eslint-plugin-import@^2.25.2
√ Would you like to install them now? · No / Yes
√ Which package manager do you want to use? · npm
Installing eslint-config-airbnb-base@latest, eslint@^7.32.0 || ^8.2.0, eslint-plugin-import@^2.25.2
npm WARN notsup Unsupported engine for eslint@8.41.0: wanted: {"node":"^12.22.0 || ^14.17.0 || >=16.0.0"} (current: {"node":"14.15.4","npm":"6.14.10"})
npm WARN notsup Not compatible with your version of node/npm: eslint@8.41.0
npm WARN notsup Unsupported engine for @eslint/eslintrc@2.0.3: wanted: {"node":"^12.22.0 || ^14.17.0 || >=16.0.0"} (current: {"node":"14.15.4","npm":"6.14.10"})
npm WARN notsup Not compatible with your version of node/npm: @eslint/eslintrc@2.0.3
npm WARN notsup Unsupported engine for @eslint-community/eslint-utils@4.4.0: wanted: {"node":"^12.22.0 || ^14.17.0 || >=16.0.0"} (current: {"node":"14.15.4","npm":"6.14.10"})
npm WARN notsup Not compatible with your version of node/npm: @eslint-community/eslint-utils@4.4.0
npm WARN notsup Unsupported engine for @eslint/js@8.41.0: wanted: {"node":"^12.22.0 || ^14.17.0 || >=16.0.0"} (current: {"node":"14.15.4","npm":"6.14.10"})
npm WARN notsup Not compatible with your version of node/npm: @eslint/js@8.41.0
npm WARN notsup Unsupported engine for eslint-scope@7.2.0: wanted: {"node":"^12.22.0 || ^14.17.0 || >=16.0.0"} (current: {"node":"14.15.4","npm":"6.14.10"})
npm WARN notsup Not compatible with your version of node/npm: eslint-scope@7.2.0
npm WARN notsup Unsupported engine for eslint-visitor-keys@3.4.1: wanted: {"node":"^12.22.0 || ^14.17.0 || >=16.0.0"} (current: {"node":"14.15.4","npm":"6.14.10"})
npm WARN notsup Not compatible with your version of node/npm: eslint-visitor-keys@3.4.1
npm WARN notsup Unsupported engine for espree@9.5.2: wanted: {"node":"^12.22.0 || ^14.17.0 || >=16.0.0"} (current: {"node":"14.15.4","npm":"6.14.10"})
npm WARN notsup Not compatible with your version of node/npm: espree@9.5.2

+ eslint@8.41.0
+ eslint-config-airbnb-base@15.0.0
+ eslint-plugin-import@2.27.5
added 175 packages from 77 contributors and audited 230 packages in 8.049s

73 packages are looking for funding
  run `npm fund` for details

found 3 vulnerabilities (2 high, 1 critical)
  run `npm audit fix` to fix them, or `npm audit` for details
Successfully created .eslintrc.json file in C:\Users\UVC\hyejis\backend2\nodeproj

각 항목에 대한 대답은 화살표로 골라주면 된다!

 

{
  "env": {
    "commonjs": true,
    "es6": true,
    "node": true
  },
  "extends": [
    "airbnb-base"
  ],
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parserOptions": {
    "ecmaVersion": 2018
  },
  "rules": {
    "linebreak-style": 0,
    "no-unused-vars": ["warn", { "vars": "all", "args": "after-used", "ignoreRestSiblings": false }]
  }
}

.eslintrc.json 파일을 위와 같이 수정하고

ctrl + shift + p를 눌러 workspace settings(JSON)을 선택해주면 해당 json 파일이 생성된다.

해당 json 파일에 

{
  "eslint.validate": ["javascript", "html"],
  "eslint.alwaysShowStatus": true,
  "editor.tabSize": 2,
  "git.ignoreLimitWarning": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
}

위와 같이 입력해준다.

저장해준 뒤, app.js 파일을 열면 엄청난 빨간 줄을 볼 수 있는데!

거기서 ctrl + s를 눌러주면 다시 저장되면서 오류가 사라지고 eslint 형식에 맞게 파일이 고쳐지는 것을 확인할 수 있다.

route/index.js와 /route/users.js도 마찬가지로 ctrl + s를 진행해주자!

 

모든 과정을 완료했으면 터미널에 npm run dev를 입력해준 뒤 인터넷 주소창에 localhost:3000을 입력해주자.

위의 것이 뜨면 세팅이 모두 끝난 것이다~!

 

.env 파일을 프로젝트 내에 생성해주자

NODE_ENV=development
PORT=3000
LOGGER_LEVEL=debug
DB_HOST=localhost
DB_PORT=5432
DB_DATABASE=metacamp_dev
DB_ID=postgres
DB_PASS=postgres
DB_DIALECT=postgres

다음과 같이 입력한 뒤

npm i dotenv

로 dotenv를 설치해주면 환경변수파일 .env를 만들었다!

환경변수는 구성 값 저장, 보안, 다중 환경 지원 등의 기능을 위해 사용한다.

 

const dotenv = require('dotenv');
dotenv.config();
const NODE_ENV = process.env.NODE_ENV;

app.js 파일에 위의 내용을 적어주어 env를 적용한다.

 

npm i body-parser

body-parsor를 설치해준 뒤

HTTP POST 요청 처리, 

const bodyParser = require('body-parser');
app.use(bodyParser);

 

app.js에 마찬가지로 body-parser를 사용하기 위해 require로 불러와 app.use로 사용해준다.

 

npm i winston 
npm install winston-daily-rotate-file --save

로깅처리를 하는 winston 설치

두 번째 줄 구문은 매일 날짜에 맞춰 로그를 자동으로 생성해주는 라이브러리다.

 

https://www.npmjs.com/

 

npm

Bring the best of open source to you, your team, and your company Relied upon by more than 17 million developers worldwide, npm is committed to making JavaScript development elegant, productive, and safe. The free npm Registry has become the center of Java

www.npmjs.com

위 사이트에서 winston을 검색해 나온 결과 중 가장 맨 위의 것이 winston에 해당된 페이지다.

클릭해 usage 부분에서 코드를 긁어온다.

다들 처음보는 라이브러리는 이렇게 사용한다고 한다!

 

내 경우, 다음과 같이 작성해줬다!

const { createLogger, format, transports } = require('winston');
require('winston-daily-rotate-file');
const dotenv = require('dotenv');
const fs = require('fs');

dotenv.config();

// logger level 세팅
const loggerLevel = process.env.LOGGER_LEVEL || 'info';

// const { env } = envConfig;
const logDir = 'log';

// Log only if info.level less than or equal to this level
// { error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 }

// log directory
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir);
}

// log file
const dailyRotateFileTransport = new transports.DailyRotateFile({
  // 로그파일 출력 세팅
  filename: `${logDir}/%DATE%.log`,
  datePattern: 'YYYY-MM-DD',
  format: format.combine(
    format.printf(
      (info) => `${info.timestamp}[${info.level}] ${info.message}`,
    ),
  ),
});

const logger = createLogger({
  // 로거 환경 세팅(기본 세팅)
  level: loggerLevel,
  format: format.combine(
    // format.label( { label: 'label123' }),
    format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
    format.json(),
  ),
  transports: [
    new transports.Console({
      // 콘솔 출력 세팅
      level: loggerLevel,
      format: format.combine(
        format.colorize(),
        format.printf(
          (info) => `${info.timestamp}[${info.level}] ${info.message}`,
        ),
      ),
    }),
    dailyRotateFileTransport,
  ],
});

module.exports = logger;

 

cors

Cross-origin Resource Sharing

웹 어플리케이션에서 다른 도메인이나 포트에서 리소스를 요청할 깨 발생하는 보안 정책을 해결하기 위한 메커니즘

설정 안하면 동일 출처 정책에 의해 요청 차단됨

cors를 설치하자.

npm install cors --save

환경 파일을 다음과 같이 설정해준다.

{
  "origin": ["http://localhost:3000"],
  "methods": ["OPTIONS", "GET", "POST", "HEAD", "PUT", "DELETE"]
}

app.js에 쓰기!

const cors = require('cors');
const corsConfig = require('./config/corsConfig.json');
const logger = require('./lib/logger');

app.use(cors(corsConfig));
app.use(express.json());

DB의 클라이언트 파일을 다운로드 한다.우리는 mysql을 사용했으므로 mysql을 다운받았다.

npm install mysql2 --save

DB 접속을 하기위해 sequalize를 설치한다.

npm install sequelize --save

이것도 npmjs 홈페이지에서 검색해서 가져와주자.

 

.env에서

NODE_ENV=development
PORT=3000
LOGGER_LEVEL=debug
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=metacamp_dev
DB_ID=root
DB_PASS=1234
DB_DIALECT=mysql
 

요렇게만 작성하면 error가 뜨는데, 이때 workbench에 가서

create database metacamp_dev;

위 구문을 입력한 뒤 ctrl + enter를 해준 후 다시 npm run dev를 해주면 정상적으로 실행되는 것을 확인할 수 있다.

 

디비버

여러 데이터베이스 프로그램들을 사용할 수 있게 해주는 프로그램

https://dbeaver.io/download/

 

Download | DBeaver Community

Download Tested and verified for MS Windows, Linux and Mac OS X. Install: Windows installer – run installer executable. It will automatically upgrade version (if needed). MacOS DMG – just run it and drag-n-drop DBeaver into Applications. Debian package

dbeaver.io

 

ORM

Object-Relational-Mapping

객체와 DB 간의 매핑을 자동으로 처리해주는 도구 또는 기술

객체 관계 매핑, SQL 자동 생성, DB 연산 간소화, 객체 지향 프로그래밍의 이점생산성 향상, 데이터베이스 독립성, 객체 지향 프로그래밍의 이점 활용(상속, 다형성, 캡슐화), 유지 보수 용이성

학습 곡선이 점점 올라감, 복잡할 시 성능 저하 문제, 제한된 DB 기능, ORM 자체의 복잡성

ㅇㅇ

 

 

 

 

 

 

 

728x90
반응형

댓글

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."