- 템플릿 엔진 -

응답으로 보내줄 웹페이지 모양을 미리 만들어 표준화한 것을 템플릿 이라고 한다. 

 

express-generator 가 적용된 경로 기준으로 app.js에서 템플릿 엔진에 대한 설정을 해야한다.

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

* views는 템플릿 파일들이 담긴 폴더의 위치를 지정한다.

res.render 메서드가 이 폴더를 기준으로 템플릿 엔진을 찾아서 렌더링하며

res.render('index') 라면 views.index.pug 를 렌더링 하고.

res.render('admin/main') 라면 views/admin.main.pug 를 렌더링 한다.

 

* view engine은 어떠한 종류의 템플릿 엔진을 사용할지를 나타낸다.

 

- ejs -

ejs 모듈은 웹페이지를 동적으로 처리하는 템플릿 엔진 모듈로 특정 형식의 문자열을 HTML 문자열로 변환해 준다.

 

test.ejs

<h1><%= table_name %></h1>
<hr />
<% for(let i =1; i < 10; i++) { %>
<h2><%= number %> X <%= i %> = <%= number * i %></h2>
<% } %>
 

 

const ejs = require('ejs');
const fs = require('fs');
const http = require('http');

http.createServer((request, response) => {
fs.readFile('test.ejs', 'utf-8', (error, data) => {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(
ejs.render(data, { //ejs 문자열을 HTML 문자열로 변경
/*속성값 전달*/
table_name: 'Multiplication table 19 X ?',
number: '19',
}));
});
}).listen(50000, () => { //port 50000 으로 서버실행 http://127.0.0.1:50000으로 접속가능
console.log('서버가 동작 중입니다, http://127.0.0.1:50000');
});

 

<%CODE%> : Javascript 코드 입력

<%=VALUE%> : 데이터 출력

 

 

- pug -

 

pug 모듈도 ejs 모듈처럼 템플릿 엔진 모듈이다. pug 모듈 또한 특정 형식의 문자열을 HTML 형식의 문자열로 변환 가능하다.

style.

 style 태그를 입력할 때 사용, style + '.'

 script.

 script 태그를 입력 할 때 사용, script + '.'

 //

 주석 처리

 #

 div 태그

 .

 div class 속성

 ul

 ul 태그

 li

 li 태그

 #{값}

 데이터를 출력할 때 사용

 -

 Javascript를 입력할 때 사용

 = 값

 데이터를 출력할 때 사용 

 

 

test.pug

html
head
title Pug example page
style.
body {
color: lightskyblue;
}

h1 {
color: blue;
}
script.
let name = prompt("What is your name", "");
alert("I'm " + name);
body
// annotation
#header
h1 Hello Pug module
h2 Nice to meet you
.url
a(href="https://github.com/pugjs/pug", data-set="multiple Attribute") Github for pug
ul
li Item A
li Item B
li Item C

pug 기본 형식에서 가장 중요한 것은 띄어쓰기이며 Tab 또는 띄어쓰기 중 하나를 화용해 들여쓰기를 해야 오류가 발생하지 않는다.

정보를 입력하고 싶을 때는 지정한 태그 밑에 한 단계 더 들여쓰기를 한 후 입력한다. 태그에 속성 여러개를 입력할 때는 쉼표를 사용한다.

작성된 pug 파일을 살펴보면 HTML 보다는 조금 더 직관적으로 간결하다고 느낄 수 있다.

 

const pug = require('pug');
const fs = require('fs');
const http = require('http');

http.createServer((request, response) => {
fs.readFile('test.pug', 'utf-8', (error, data) => {
response.writeHead(200, { 'Content-Type': 'text/html' });
const fn = pug.compile(data); //pug 문자열을 HTML 문자열로 변경할 수 있는 함수를 생성한다.
response.end(fn());
});
}).listen(50000, () => {
console.log('서버가 동작 중입니다, http://127.0.0.1:50000');
});

 

test2.pug

html
head
title Pug example page
body
style.
h1 #{table_name}
h2 #{number}
hr
- for(let i =1; i < 10; i++) {
p
#multiple
#{number} X #{i} = #{number * i}
- }

 

 

const pug = require('pug');
const fs = require('fs');
const http = require('http');

http.createServer((request, response) => {
fs.readFile('test2.pug', 'utf-8', (error, data) => {
response.writeHead(200, { 'Content-Type': 'text/html' });
const fn = pug.compile(data);
response.end(fn());
});
}).listen(50000, () => {
console.log('서버가 동작 중입니다, http://127.0.0.1:50000');
});

 

'공부 > Node.js' 카테고리의 다른 글

express  (0) 2019.03.08
로그 - winston 모듈  (0) 2019.03.08
크롤링 - cheerio, iconv-lite 모듈  (1) 2019.03.07
npm  (0) 2019.03.06
http 모듈  (0) 2019.03.06
const request = require('request');
const iconv = require('iconv-lite');

request({
url: 'https://www.google.com/search',
method: 'GET',
qs: { q: '신사역 맛집' },
encoding: null,
}, (error, response, body) => {
const decodedResult = iconv.decode(body, 'euc-kr');
console.log(decodedResult);
});


한글이 깨지는 문제가 있을 때 request 옵션으로 encoding을 null로 설정한 후 iconv-lite 모듈을 이용해 euc-kr로 디코드 해주면 된다.


crawler.js

const request = require('request');
const iconv = require('iconv-lite');
const charset = require('charset');

const crawl = callback => queryString => request({
url: 'https://www.google.com/search',
encoding: null, //한글이 깨지는 문제를 해결하기 위해 null로 설정
method: 'GET', //GET 요청
qs: queryString, //크롤러를 이후 사용할 때 인자로 전달되는 값
timeout: 10000, //10초 이후 응답을 포기
followRedirect: true, //사이트 이동을 허용할 것인지 체크
maxRedirects: 10, //리다이렉션을 최대 몇 번 할지 설정
},
(error, response, body) => {
if (!error && response.statusCode === 200) { //HTTP 상태코드가 200이면 서버가 요청을 제대로 처리했다는 뜻이다.
const enc = charset(response.headers, body); //현재 사이트의 헤더 정보에서 인코딩 정보를 가져옴
const decodedResult = iconv.decode(body, enc); //iconv를 이용하여 해당 사이트의 인코딩 방식으로 body를 디코드
callback(decodedResult); //디코드 결과를 콜백
} else {
console.log(`error${response.statusCode}`);
}
});

module.exports.crawl = crawl; //작성한 크롤러 객체를 외부에서 사용할 수 있도록 모듈을 추출



const crawler = require('./crawler');
const cheerio = require('cheerio');
const fs = require('fs');

const parse = (decodedResult) => { //디코드 결과가 콜백으로 넘어옴
const $ = cheerio.load(decodedResult); //검색한 결과를 $변수에 로드
const titles = $('h3.r').find('a'); //클래스명으로 r을 가진 h3 요소 중 하위 요소가 a인 데이터를 모두 찾아서 반환
titles.each((index, element) => { //titles의 검색 결과를 each를 통해 element 단위로 받아옴
const title = $(element).text(); //요소의 값을 추출후 저장
console.log(title);
fs.appendFile('./titles.txt', `${title}\n`); //titles.txt가 존재 하지않으면 생성하고 해당 내용을 붙여나감
});
};

crawler.crawl(parse)({ q: '샤로수길 맛집' }); //크롤링 결과를 parse 콜백함수에 넘겨주게 호출


'공부 > Node.js' 카테고리의 다른 글

로그 - winston 모듈  (0) 2019.03.08
템플릿 엔진 모듈 - ejs, pug 모듈  (0) 2019.03.07
npm  (0) 2019.03.06
http 모듈  (0) 2019.03.06
fs 모듈  (0) 2019.03.06

/*프로젝트 초기화 하기*/

npm init

package name 패키지의 이름. package.json의 name 속성에 저장된다.
version 패키지의 버전.
entry point 자바스크립트 실행 파일 진입점. package.json의 main 속성에 저장된다.
test command 코드를 테스트할 때 입력할 명령어. package.json의 scripts 속성 안에 test 속성에 저장된다.
git repository 코드를 저장해둔 Git 저장소 주소. package.json의 repository 속성에 저장된다.
keywords 키워드는 npm 공식 홈페이지에서 패키지를 쉽게 찾을수 있게 해준다. package.json의 keywords 속성에 저장된다.
license 해당 패키지의 라이선스

 

/* 패키지 설치 */

npm install 모듈명 --save

@^1.1.1

1.1.1 <= 버전 < 2.0.0 까지 설치

@~1.1.1

1.1.1 <= 버전 < 1.2.0 까지 설치

@>1.1.1

1.1.1 버전보다 높은 버전이 설치

@latest or @x

항상 최신 버전의 패키지를 설치

 

*install 은 i로 줄여쓸 수 있다.

* 모듈명을 여러 개 입력해서 동시에 설치가능하다.

 

--save

*옵션을 사용하지 않으면 package.json의 dependencies에 등록이 되지 않는다. 하지만 npm@5 부터는 기본값으로 설정되어 있으므로 따로 붙이지 않아도 된다.

 

--save-dev

*devDependencies 에 추가함. 개발할 때만 필요한 패키지를 명시하는 경우 사용된다. -D로 줄여쓸 수 있다.

* 패키지를 설치할 경우 해당 패키지가 의존하는 다른 패키지들이 같이 설치된다.

* 설치한 패키지들은 node_modules 폴더에 들어 있다.

 

--global

*-g로 줄여쓸수있다.

* 전역 설치 라는 옵션으로 패키지를 node_modules에 설치하는 것이 아니라 npm이 설치되어 있는 폴더에 설치한다. 이 폴더의 경로는 시스템 환경 변수에 등록되어 있으며 전역 설치한 패키지는 콘솔의 커맨드로 사용할 수 있다.

* 전역 설치한 패키지는 package.json에 기록되지 않는다.

 

npx

*package.json에 패키지를 기록하고 전역설치 또한 하고싶다면

npm install --save-dev rimraf

npx rimraf node_modules

위와 같이 모듈을 package.json의 devDependencies 속성에 기록한 후 npx를 명령어를 실행해 패키지를 전역 설치한 것과 같은 효과를 얻을 수 있다.

 

npm install [저장소 주소]

*npm에 등록되지 않은 일부 패키지의 경우 GitHub이나 nexus 등의 저장소에 보관되어 있을 수도 있는데 그럴 경우 패키지명 대신 저장소 주소를 명시하면 설치가 가능하다.

 

/* 패키지 지우기 */

npm uninstall

* rm으로 줄여 쓸수도 있다.

* --save 옵션을 사용하지 않으면 package.json에서 삭제되지 않는다..

* --save-dev devDependencies 에서 삭제함.

* node_modules 폴더를 삭제했을 경우 설치한 패키지는 지워졌지만 package.json에 설치한 패키지 내역이 들어 있으므로 npm install 명령어 실행시 다시 설치된다.

 

/* 패키지 업데이트 */

npm update [패키지명]

명시한 패키지를 업데이트 한다. npm update 까지만 실행하면 업데이트 가능한 모든 패키지가 Wanted에 적힌 버전으로 업데이트 된다.

 

npm outdated

*업데이트 할 수 있는 패키지가 있는지 확인

Package Current Wanted Latest Location
body-parser 1.17.2 1.18.1 1.18.1 경로
express 4.15.0 4.15.4 4.15.4 경로

Current와 Wanted가 다르다면 업데이트가 필요한 경우이다.

 

/* 패키지 검색 */

npm search [검색어]

* npm 패키지를 검색할 수 있다. 

 

npm info [패키지명]

* 패키지의 세부 정보를 파악하고자 할 대 사용하는 명령어이다. package.json의 내용과 의존 관계, 설치 가능한 버전 정보 등이 표시된다.

 

/* npm 로그인 */

npm adduser

* npm 로그인을 위한 명령어로 npm 공식 사이트에서 가입한 계정으로 로그인 가능하다. 나중에 패키지를 배포할 때 로그인이 필요하며 패키지를 배포하지 않을것이라면 npm에 가입할 필요는 없다.

 

npm whoami

* 로그인한 사용자가 누구인지 알려준다. 로그인된 상태가 아니라면 에러가 발생한다.

 

npm logout

* npm adduser로 로그인한 계정을 로그아웃할 때 사용한다.

 

/* 버전 갱신 */

npm version [버전]

* package.json의 버전을 올려준다. major, minor, patch 라는 문자열을 넣어서 해당 부분의 숫자를 1 올릴 수도 있다.

ex) npm version 5.3.2, npm version minor

 

/* 경고 삽입 */

npm deprecate [패키지명][버전] [메시지]

* 해당 패키지를 설치할 때 경고 메시지를 띄우게 하는 명령어로 자신의 패키지에만 쓸 수 있다. deprecated 처리를 해두면 다른 사용자들이 버그가 있는 버전의 패키지를 설치할 때 경고 메시지가 출력된다.

 

/* 배포 */

npm publish

* 자신이 만든 패키지를 배포할 때 사용한다.

 

npm unpublish

배포한 패키지를 제거할 때 사용한다. 24시간 이내에 배포한 패키지만 제거할 수 있다.

이러한 제약이 있는 이유는 의존성 관계 때문이며 다른 사람이 사용하고 있는 패키지를 제거하는 경우를 막기 위해서이다.

 

- 모듈 -

request

* 서버에 요청을 보낼 때 request 모듈을 이용한다.

 

cheerio

* cheerio 모듈은 jQuery 기반 문법을 지원한다. 웹 페이지에서 받아온 내용에서 원하는 데이터를 추출하기 위해 사용할 수 있는 find() 등 다양한 메소드를 제공한다.

 

inconv-lite

* incov 모듈(node-iconv)는 다양한 인코딩을 제공하는 반면 네이티브 코드 컴파일이 필요한 반면, iconv-lite는 그러한 컴파일 과정이 필요 없는 순수한 자바스크립트이다. 또한 보다 사용이 쉽다.

 

nodemon

* 소스코드가 바뀔 때마다 자동으로 노드를 재실행해준다.

 

rimraf

* 리눅스나 macOS의 rm -rf 명령어를 윈도우에서도 사용할 수 있게 해주는 패키지이다.

'공부 > Node.js' 카테고리의 다른 글

템플릿 엔진 모듈 - ejs, pug 모듈  (0) 2019.03.07
크롤링 - cheerio, iconv-lite 모듈  (1) 2019.03.07
http 모듈  (0) 2019.03.06
fs 모듈  (0) 2019.03.06
API 읽는 법 - fs.access(path[,mode],callback)  (0) 2019.03.06


http 모듈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// http 모듈 sever 객체
// 웹 서버 생성과 실행
const http = require('http');
 
const server = http.createServer();
 
server.listen(50000, () => {
  console.log('서버가 동작 중입니다, http://127.0.0.1:50000');
});
 
// 웹서버 종료
const testClose = function () {
  server.close();
  console.log('서버가 종료되었습니다, http://127.0.0.1:50000');
};
 
// 강제 서버종료
setTimeout(testClose, 5000);
cs


event

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
31
// http 모듈 sever 객체의 이벤트
// 웹 서버 생성과 실행
const http = require('http');
 
const server = http.createServer();
 
// 이벤트 연결
server.on('request', () => {
  console.log('Request');
});
 
server.on('connection', () => {
  console.log('Connection');
});
 
server.on('close', () => {
  console.log('Close');
});
 
server.listen(50000, () => {
  console.log('서버가 동작 중입니다, http://127.0.0.1:50000');
});
 
// 웹서버 종료
const testClose = function () {
  server.close();
  console.log('서버가 종료되었습니다, http://127.0.0.1:50000');
};
 
// 강제 서버종료
setTimeout(testClose, 10000);
cs


response 객체

1
2
3
4
5
6
require('http').createServer((request, response) => {
  response.writeHead(200, { 'Content-Type''text/html' });
  response.end('Hello World!');
}).listen(50000, () => {
  console.log('서버가 동작 중입니다, http://127.0.0.1:50000');
});
cs


response 객체, fs 모듈 활용 1

1
2
3
4
5
6
7
8
9
10
11
const fs = require('fs');
const http = require('http');
 
http.createServer((request, response) => {
  fs.readFile('./test.html', (error, data) => {
    response.writeHead(200, { 'Content-Type''text/html' });
    response.end(data);
  });
}).listen(50000, () => {
  console.log('서버가 동작 중입니다, http://127.0.0.1:50000');
});
cs


response 객체, fs 모듈 활용 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const fs = require('fs');
const http = require('http');
 
http.createServer((request, response) => {
  fs.readFile('./test.jpg', (error, data) => {
    response.writeHead(200, { 'Content-Type''image/jpeg' });
    response.end(data);
  });
}).listen(50001, () => { //50001 포트
  console.log('서버가 동작 중입니다, http://127.0.0.1:50001');
});
 
http.createServer((request, response) => {
  fs.readFile('./Cullah_DaftPunk.mp3', (error, data) => {
    response.writeHead(200, { 'Content-Type''audio/mp3' });
    response.end(data);
  });
}).listen(50002, () => { //50002 포트
  console.log('서버가 동작 중입니다, http://127.0.0.1:50002');
});
cs


타입 

일반적인 서브타입 예시 

설명 

text 

text/plain, text/html, text/css, text/javascript 

텍스트를 포함하는 모든 문서를 나타내며 이론상으로는 인간이 읽을수 있어야한다. 

image

image/gif, image/png, image/jpeg, image/bmp, image/webp 

모든 종류의 이미지를 나타내며 애니메이션되는 이미지가 이미지 타입에 포함되긴 하지만 비디오는 포함되지 않는다. 

audio 

audio/midi, audio/mpeg, audio/webm, audio/ogg, audio/wav 

모든 종류의 오디오 파일을 나타낸다. 

video 

video/webm, video/ogg 

모든 종류의 비디오 파일을 나타낸다. 


request 객체, url 속성 활용

const fs = require('fs');
const http = require('http');
const url = require('url');

http.createServer((request, response) => {
let pathname = url.parse(request.url);
pathname = url.parse(request.url).pathname;

if (pathname === '/') {
fs.readFile('./138_index.html', (error, data) => {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(data);
console.log(url.parse(request.url));
});
} else if (pathname === '/example') {
fs.readFile('./136_example.html', (error, data) => {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(data);
console.log(url.parse(request.url));
});
}
}).listen(50000, () => {
console.log('서버가 동작 중입니다, http://127.0.0.1:50000');
});


request 객체의 속성

url 

요청한 URL 정보 

headers 

요청 메시지 헤더 정보 

method 

클라이언트의 요청 방식 

httpVersion 

HTTP 프로토콜의 버전 



- GET, POST -

test.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Example for POST</h1>
<form method = "post"> /*post 방식. get이라 적으면 get방식이다*/
<table>
<tr>
<td>Soju</td>
<td><input type = "text" name = "beverage_1"/></td>
</tr>
<td>Beer</td>
<td><input type = "text" name = "beverage_2"/></td>
</table>
<input type = "submit" />
</form>
</body>
</html>


const http = require('http');
const fs = require('fs');

http.createServer((request, response) => {
/*http 프로토콜에서 메시지를 요청하는 방법 중 가장 많이 사용하는 GET, POST 방식*/
if (request.method === 'GET') { //GET 요청일 경우. request의 method 속성을 사용하여 구분
fs.readFile('./test.html', (error, data) => {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(data);
console.log(`${request.method}방식의 요청입니다`);
});
} else if (request.method === 'POST') { //POST 요청일 경우. 여러개의 값을 숨겨서 보낼수있다.
request.on('data', (data) => {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(data);
console.log(`${request.method}방식의 요청입니다`);
});
}
}).listen(50000, () => {
console.log('서버가 동작 중입니다, http://127.0.0.1:50000');
});



'공부 > Node.js' 카테고리의 다른 글

템플릿 엔진 모듈 - ejs, pug 모듈  (0) 2019.03.07
크롤링 - cheerio, iconv-lite 모듈  (1) 2019.03.07
npm  (0) 2019.03.06
fs 모듈  (0) 2019.03.06
API 읽는 법 - fs.access(path[,mode],callback)  (0) 2019.03.06

파일로 출력하기 - fs.writeFile()

1
2
3
4
const fs = require('fs');
 
const contents = 'hello\nbye\n안녕';
fs.writeFile('./message.txt', contents);
cs


동기로 파일 열기 - fs.readFileSync()

1
2
3
4
5
6
const fs = require('fs');
 
const data = fs.readFileSync('./message.txt');
const string = data.toString();
console.log('sync work01');
console.log(string);
cs


비동기로 파일 열기 - fs.readfile()

1
2
3
4
5
6
7
const fs = require('fs');
 
fs.readFile('./message.txt', (err, data) => {
  if (err) throw err;
  console.log('async work01');
  console.log(data.toString());
});
cs


파일 내용 수정하기

1
2
3
4
5
6
7
8
const fs = require('fs');
 
fs.readFile('./message.txt', (err, data) => {
  if (err) throw err;
  let contents = data.toString();
  contents = 'replaced';
  fs.writeFile('./message.txt', contents);
});
cs


파일에 내용 수정하기 - fs.appendFile()

1
2
3
4
5
const fs = require('fs');
 
const list = [12345];
 
list.forEach(item => fs.appendFile('./chapters.txt', `chapter ${item}\n`));
cs


디렉토리 만들기 fs.mkdirSync()

1
2
3
4
5
6
7
const fs = require('fs');
 
const dirName = `${__dirname}/img`;
 
if (!fs.existsSync(dirName)) {
  fs.mkdirSync(dirName);
}
cs


파일 리스트 출력하기

1
2
3
4
5
6
7
8
const testFolder = './';
const fs = require('fs');
 
const filenameList = fs.readdirSync(testFolder);
 
filenameList.forEach((fileName) => {
  console.log(fileName);
});
cs


list를 json 형식으로 파일에 저장하기 - JSON.stringify()

1
2
3
4
5
6
7
8
const fs = require('fs');
 
const userList = [
  { name'kyeongrok', age: 31 },
  { name'jihyun', age: 31 },
];
 
fs.writeFile('./list.json', JSON.stringify(userList));
cs


파일을 json 형식으로 불러오기 - JSON.parse()

1
2
3
4
5
6
7
8
const fs = require('fs');
 
fs.readFile('./list.json', (err, data) => {
  if (err) throw err;
  const json = JSON.parse(data.toString());
  console.log('name:', json[0].name);
  console.log('name:', json[1].name);
});
cs


파일 이름 바꾸기

1
2
3
4
5
6
7
8
9
10
11
12
const fs = require('fs');
 
const renameFile = (fromFilePathName, toFilePathName) => {
  fs.rename(fromFilePathName, toFilePathName, (err) => {
    if (err) console.log(`ERROR: ${err}`);
  });
};
 
const fromFilePathName = './hello.txt';
const toFilePathName = './bye.txt';
 
renameFile(fromFilePathName, toFilePathName);
cs


'공부 > Node.js' 카테고리의 다른 글

템플릿 엔진 모듈 - ejs, pug 모듈  (0) 2019.03.07
크롤링 - cheerio, iconv-lite 모듈  (1) 2019.03.07
npm  (0) 2019.03.06
http 모듈  (0) 2019.03.06
API 읽는 법 - fs.access(path[,mode],callback)  (0) 2019.03.06
1
2
3
4
5
6
7
8
/*
fs.access(path[,mode],callback);
대괄호는 옵션. mode는 입력해도되고 안해도된다.
*/
 
const fs = require("fs");
fs.access("c:\practice\message.txt", (string)=>console.log(string));
 
cs


'공부 > Node.js' 카테고리의 다른 글

템플릿 엔진 모듈 - ejs, pug 모듈  (0) 2019.03.07
크롤링 - cheerio, iconv-lite 모듈  (1) 2019.03.07
npm  (0) 2019.03.06
http 모듈  (0) 2019.03.06
fs 모듈  (0) 2019.03.06

+ Recent posts