Created
June 21, 2017 16:18
-
-
Save Curookie/7aed2c2d94a7ec256c33e5cc3b4094c8 to your computer and use it in GitHub Desktop.
node.js 정리
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
express-generator 를 설치하면 좋다. | |
-g 글로벌 옵션 | |
npm install을 하면 package.json의 dependencies를 바탕으로 설치하게 된다. | |
설치가 완료 된 후의 디렉토리 구조는 다음과 같다. | |
. | |
├── app.js | |
├── bin | |
│ └── www | |
├── package.json | |
├── public | |
│ ├── images | |
│ ├── javascripts | |
│ └── stylesheets | |
│ └── style.css | |
├── routes | |
│ ├── index.js | |
│ └── users.js | |
├── views | |
│ ├── error.ejs | |
│ └── index.ejs | |
└── node_modules | |
├── body-parser | |
├── cookie-parser | |
├── debug | |
├── ejs | |
├── express | |
├── morgan | |
├── node-sass-middleware | |
└── serve-favicon | |
이외의 모듈을 설치하고 싶다면 아래와 같이 하면 되고 | |
$ npm install [module이름] | |
설치할 모듈을 package.json의 dependency에 넣고 싶다면 --save 옵션을 붙이면 된다. | |
ex) | |
npm install express --save | |
참고로 설치된 패키지를 지우고 싶을때는 install 대신에 uninstall을 쓰면 된다. | |
npm uninstall express --save | |
어플리케이션을 작성할 때 모든 dependency되는 모듈들은 require()를 이용해야 한다. | |
var express = require('express'); | |
var path = require('path'); | |
var favicon = require('serve-favicon'); | |
var logger = require('morgan'); | |
var cookieParser = require('cookie-parser'); | |
var bodyParser = require('body-parser'); | |
다음 express객체를 초기화하고 express세팅을 설정하는 과정을 거친다. | |
var app = express(); | |
app.set('views', path.join(__dirname, 'views')); | |
app.set('view engine', 'ejs'); | |
위와 같이 app.set()을 이용해서 express의 세팅을 할 수 있다. | |
app.use(logger('dev')); | |
app.use(bodyParser.json()); | |
app.use()를 사용하는 부분은 express에서 흔히 말하는 미들웨어 부분이다. app.use(logger('dev'))와 같이 모듈의 이름이 써 있는 경우는 미들웨어의 역할을 외부모듈에서 해주는 경우이다. 여기에서는 외부모듈을 설정해주는 부분이라고 생각하면 쉬울 듯 하다. | |
에러핸들러는 에러가 발생했을 때 어떻게 처리할지에 대한 문제이다. 보통 에러처리가 잘 되어 있는 프로그램을 잘 만들어진 프로그램이라고 말 할 정도로 중요한 부분이다. 기본적으로는 에러가 발생하면 메세지 처리를 한다. | |
app.use(function(err, req, res, next) { | |
res.status(err.status || 500); | |
res.render('error', { | |
message: err.message, | |
error: {} | |
}); | |
}); | |
위의 구문을 사용하면 에러가 발생했을 경우에 에러에 관련된 메세지를 화면에 보여주게 된다. | |
ejs = embeded javascript | |
ejs는 html과 같은 문법을 사용하기 때문에 html에 대한 경험이 있는 사람은 쉽게 접근할 수 있다. | |
다만 여기에서 변수나 서버에서 보내는 데이터를 표현하기 위해서는 <% … %>를 사용하게 된다. | |
<% ... %> 을 사용하는 경우는 함수나 분기문등을 사용할 때 쓰고, | |
<%= ... %> 는 변수를 넣어서 화면에 표시해주기 위해 사용한다. | |
<%= ... %>로 보내질 데이터는 res.render('index', { title: 'Express' }); 의 부분에서 {title:'Express'} 이고, | |
렌더링을 할 때 title은 ‘Express’로 바뀌어져 화면에 보여지게 된다. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment