Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

what i learned

[Node.js] 프로젝트 생성 후 초기 세팅하기 본문

Web Development/Node.js

[Node.js] 프로젝트 생성 후 초기 세팅하기

햄식이111 2022. 8. 19. 01:01

1. express 프로젝트 생성하기

npm 전역설치
$ npm i -g express-generator

$ express 프로젝트명

생성한 프로젝트에 들어가서
$ cd 프로젝트

서버를 돌리기 위해 필요한 것 설치
$ npm i

서버 계속 돌리기 위한 패키지 설치
$ npm install -D nodemon

+) nodemon을 설치했다면 package.json 파일에서 nodemon으로 수정해야한다.

"scripts": {
    "start": "nodemon ./bin/www"
  },

 

 

2. 필요한 폴더 및 파일 생성하기

1) .env 파일 생성 (환경변수를 관리하는 파일)

DATABASE = 데이터베이스명
PASSWORD = MySQL비밀번호
USERNAME = root
HOST = localhost	//localhost 오류 발생 시 127.0.0.1 로 사용
PORT = 3306		//PORT 번호 입력 시 bin/www 파일의 process.env.PORT 삭제하기

위에서 주석처리는 삭제해줘야함! .env파일에서는 //가 주석이 아니라서 오류가 발생한다.

+) PORT 번호 작성 시 bin폴더의 www 파일에서 .env의 PORT 번호는 삭제해주기

//var port = normalizePort(process.env.PORT || '3000');
//app.set('port', port);
// 위의 코드 대신 아래의 코드 작성

var port = normalizePort('3000');
app.set('port', port);

 

2) configs 폴더 생성

- index.js 파일 생성

const mysql = require('mysql2/promise');
const dotenv = require('dotenv');

dotenv.config();

const dbConfig = {
    host: process.env.HOST,
    port: 3306,
    user: process.env.USERNAME,
    password: process.env.PASSWORD,
    database: process.env.DATABASE
}

const connection = mysql.createPool(dbConfig);

console.log(connection)

module.exports = connection

 

3) .gitignore 파일 생성

.gitignore파일은 아래 사이트에서 쉽게 생성할 수 있다.

(python, pycharm, visualstudiocode, vim, macos, linux, zsh을 기입하여 생성한다.)

https://www.toptal.com/developers/gitignore

위 사이트에서 작성한 gitignore 파일 말고도 환경변수를 관리해주는 .env파일처럼 유출되면 안되는 파일들도 같이 넣어줘야한다.

// .gitignore파일에 아래의 파일들도 추가한다.
node_modules
.env
package-lock.json

+) 프로젝트 생성 후 node_modules 디렉터리가 없다면 아직 외부 패키지를 다운받지 않았기 때문이다. 외부 패키지를 다운로드 하면 자동으로 생성된다!

 

4) models 폴더 생성

- userDao.js 같은 필요한 데이터 모델 파일을 만들 수 있음

ex) models 안에 daos, entity폴더를 만든 후 entity폴더에 index.js, users.entity.js로 생성할 수도 있고,

      models안에 바로 userDao.js, likeDao.js, postDao.js 를 작성할 수도 있음

 

 

 


공부한 내용을 기록하는 공간입니다.

잘못된 정보가 있을 경우 댓글로 피드백 주세요.

올바른 지식을 알려주셔서 감사합니다:)