1. Node.js
① 백엔드 개발자가 사용하는 언어이다.
② 서버에서 실행되는 자바스크립트이다.
③ Google V8 JavaScript 엔진을 사용하여 코드를 실행하고 기본 모듈이 자바스크립트로 사용된다.
④ node.js에는 웹 서버 소프트웨어가 필요없이 웹 서버 역할을 할 수 있는 내장 라이브러리가 있다.
⑤ NPM이라는 패키지 관리자가 포함되어 있다. NPM은 node..js의 프로그램을 설치하고 관리하는데 사용된다.
2. Node.js 다운로드(LTS 버전으로 받기!)
** 국비 수업에서 다운받았음 -> https://shine94.tistory.com/107
[node.js 버전 확인] cmd 창에서 node -v 명령어, [npm 버전 확인] cmd 창에서 npm -v 명령어
** LTS 버전 : 안정화된 버전, Current 버전 : 최신 버전
3. 1_Hello.js
console.log('안녕하세요. Node.js');
4. package.json 파일 만들기
: 모듈을 관리하는 설정파일
[npm init] 옵션을 직접 제공
[npm init -y] 기본값을 기준으로 바로 생성
5. node.js 실행하는 방법
node 파일이름
6. 2_About.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
7. FileSystem 모듈(=FS)
: 파일처리와 관련된 모듈이다.
node.js에서 가장 중요하고 기초가 되는 모듈이다.
** 메소드
readFile() : 파일을 비동기적으로 읽는다.
readFileSync() : 파일을 동기적으로 읽는다.
writeFile() : 파일을 비동기적으로 쓴다.
writeFileSync() : 파일을 동기적으로 쓴다.
8. 동기와 비동기
: 프로그램이 동작하는 상태에서 완전히 해당 내용을 끝내고 다음으로 제어를 넘기는 방식을 동기식,
동작이 끝나지 않은 상태에서도 제어권을 넘긴 후 프로그램을 계속 진행하면 비동기식
9. readFile(), readFileSync()
** text1.txt
Hello Node.js!!
** 3_FileSystem1.js
const fs = require('fs'); // 파일을 다루는 모듈
fs.readFile('text1.txt', 'utf-8', (err, data) => { // 비동기(콜백)
if(err) {
console.log(err);
} else {
console.log(`비동기식으로 읽음 : ${data}`);
}
});
const text = fs.readFileSync('text1.txt', 'utf-8'); // 동기
console.log(`동기식으로 읽음 : ${text}`);
10. writeFile(), writeFileSync()
** 4_FileSystem2.js
const fs = require('fs');
const data = "Hello Node.js !!";
fs.writeFile('text2.txt', data, 'utf-8', (err) => {
if(err) {
console.log('에러 발생!');
} else {
console.log('저장완료 / 비동기');
}
});
fs.writeFileSync('text3.txt', data, 'utf-8');
console.log('저장완료 / 동기');
11. 예외 처리(비동기는 예외처리를 할 필요가 없고 동기는 반드시 예외처리를 해야 한다!)
: 프로그램이 실행되고 있는 런타임시에 에러가 발생할 경우 처리할 수 있는 프로그램 구간을 의미한다.
try {
예외 상황이 발생할 수 있는 문장;
...
} catch (e) {
예외 상황이 발생했을 경우 처리할 문장(e는 Excepton 객체);
} finally {
예외 상황이 발생하거나 발생하지 않아도 무조건 실행될 문장(생략 가능);
}
** 5_FileSystem3.js
const fs = require('fs');
// text11.txt 파일 없다 => 예외 처리 필요
// 비동기는 예외 처리를 할 필요가 없다
fs.readFile('text11.txt', 'utf-8', (err, data) => {
if(err) {
// 여기서 에러 처리를 하기 때문에...!
console.log('에러발생! / 비동기');
} else {}
});
// 동기는 따로 예외처리가 없기 때문에 try ~ catch 문을 이용하여 예외처리를 해줘야 한다!
try {
const text = fs.readFileSync('text11.txt', 'utf-8'); // 동기
console.log(`동기식으로 읽음 : ${text}`);
} catch(e) {
console.log('에러발생! / 동기');
}
console.log('프로그램 종료');
12. 이벤트 루프(Event Loop)
: node.js는 서버가 가동되면 변수들을 초기화하고 함수를 선언하고 이벤트가 발생할 때까지 기다린다.
이벤트가 감지되었을 때 call back 함수를 호출한다.
** events : 이벤트 위주의 프로그램을 작성할 대 사용하는 모듈
** 메소드
on() : 지정한 이벤트의 리스너를 추가한다.
once() : 지정한 이벤트의 리스너를 추가하지만 한 번 실행 이후 자동 제거된다.
removelistener() : 지정한 이벤트에 대한 리스너를 제거한다.
emit() : 지정한 이벤트를 발생시킨다.
** 6_Events.js
const events = require('events');
// 이벤트 관련 메소드를 사용할 수 있는 EventEmitter 객체를 만든다.
const eventEmitter = new events.EventEmitter();
const connectHandler = function connected() { // 2-2. connectHandler 실행
console.log('연결 성공!');
eventEmitter.emit('data_reveived'); // 3. data_reveived 이벤트 발생
}
// connection 이벤트와 connectHandler 핸들러와 연결
eventEmitter.on('connection', connectHandler); // 2-1. connection - connectHandler 연결
// data_receive 이벤트와 익명함수와 연결
eventEmitter.on('data_reveived', () => { // 4. 익명함수 실행
console.log('데이터 수신!');
});
eventEmitter.emit('connection'); // 1. connection 이벤트 발생
console.log('프로그램을 종료합니다.');
13. 시스템 이벤트
: process 객체는 노드에서 항상 사용할 수 있는 객체이다.
on()과 emit() 메소드는 객체를 생성하거나 모듈을 가져오지 않아도 바로 사용할 수 있다.
on() 메소드를 호출하면서 이벤트 이름을 exit로 지정하면 내부적으로 프로세스가 끝날 때를 알 수 있다.
** 7_Process.js
process.on('exit', () => {
console.log('exit 이벤트 발생!');
});
setTimeout(() => {
console.log('3초 후 시스템 종료');
process.exit;
}, 3000);
14. http 모듈
: node.js에서 가장 기본적이고 중요한 서버 모듈이다.
HTTP 웹 서버를 생성하는 것과 관련된 모든 기능을 담당한다.
1) server 객체
: http 모듈의 createServer() 메소드를 사용하여 server 객체를 생성한다.
** 메소드
listen() : 서버를 실행하고 클라이언트를 기다린다.
close() : 서버를 종료한다.
** 이벤트
request : 클라이언트가 서버에 요청할 때 발생하는 이벤트이다.
connection : 클라이언트가 접속할 때 발생하는 이벤트이다.
close : 서버가 종료될 때 발생하는 이벤트이다.
2) request 객체
: 클라이언트가 서버에게 전달하는 메시지(정보)를 담는 객체이다.
** 속성
method : 클라이언트 요청 방식을 나타낸다.(GET, POST)
url : 클라이언트가 요청한 URL을 나타낸다.
3) response 객체
: 서버에서 클라이언트로 응답 메시지를 전송시켜주는 객체이다.
** 메소드
writeHead() : 응답 헤더를 작성한다.
end() : 응답 본문을 작성한다.
** MIME 형식
text/plain : 일반적은 text 파일
text/html : html 형식 파일
text/css : css 형식 파일
text/xml : xml 형식 파일
image/jpeg : jpeg 이미지 파일
image/png : png 이미지 파일
video/mpeg : mpeg 동영상 파일
audio/mp3 : mp3 음악 파일
...
** http 모듈 확인 방법
http://localhost:포트번호
http://127.0.0.1:포트번호
http://자기아이피(cmd 창에서 ipconfig 명령어, IPv4 주소):포트번호
** 8_http1.js
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'content-type' : "text/html"});
res.end('<!DOCTYPE html><html lang="ko"><head><meta charset="UTF-8"><title>http 모듈 테스트</title></head>'
+ '<body style="background-color: deepskyblue;"><h2>http 모듈 테스트</h2><p>처음으로 실행하는 node.js http 서버</p></body></html>');
}).listen(3000, () => {
console.log('서버 실행중...');
});
** test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>http 모듈 테스트</title>
</head>
<body style="background-color: deeppink;">
<h2>http 모듈 테스트</h2>
<p>처음으로 실행하는 node.js http 서버</p>
</body>
</html>
** 9_http2.js
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
fs.readFile('test.html', (err, data) => {
if(err) {
console.log(err);
} else {
res.writeHead(200, {'content-type' : 'text/html'});
res.end(data);
}
});
}).listen(3000, () => {
console.log('서버 실행중...');
});
** 10_http3.js
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
fs.readFile('node.png', (err, data) => {
if(err) {
console.log(err);
} else {
res.writeHead(200, {'content-type' : 'image/png'});
res.end(data);
}
});
}).listen(3000, () => {
console.log('이미지 서버 실행중...');
});
http.createServer((req, res) => {
fs.readFile('sunny.mp3', (err, data) => {
if(err) {
console.log(err);
} else {
res.writeHead(200, {'content-type' : 'audio/mp3'});
res.end(data);
}
});
}).listen(3001, () => {
console.log('사운드 서버 실행중...');
});
15. 익스프레스 모듈(직접 다운로드 받아서 설치해야 사용 가능함!)
: http 모듈만 사용해서 웹 서버를 구성하면 직접 많은 기능을 개발해야 한다.
이 문제를 해결하기 위해 만들어진 모듈이 익스프레스이다.
익스프레스 모듈을 사용하면 간단한 코드로 웹 서버의 기능을 대부분 구현할 수 있고,
미들웨어와 라우터를 사용하여 편리하게 웹 서버를 구성할 수 있다.
** 미들웨어?
웹 서버 기능에 추가적으로 필요한 기능을 설치, 또는 사용할 수 있게 객체 여러 개를 써서 넣을 수 있는
중간에 껴있는 프로그램
** 라우터?
이 서버에 접속하게 되면 사용자를 어떤 페이지로 이동시킬지 조절해주는 기능
** 메소드
use() : 미들웨어 함수를 사용한다.
get() : get으로 사용자 정보를 전달받는다.
set() : 서버 설정을 위한 속성을 설정한다.
redirect() : 웹 페이지의 경로를 강제로 이동시킨다.
send() : 클라이언트에 응답 데이터를 보낸다, 전달할 수 있는 데이터는 html, buffer, json, json 배열 ... 등이다.
header() : 헤더를 확인한다.
** package 설치하기
npm install 모듈명(=npm i 모듈명)
npm install express(=npm i express)
** 11_express1.js
const express = require('express');
const app = express();
const port = 3000;
// localhost:3000/
app.get('/', (req, res) => {
res.send('익스프레스 서버 테스트');
});
app.listen(port, () => {
console.log(`${port} 포트로 서버 실행중...`);
});
16. package 복원하기
복원할 package + 터미널에 npm install 명령어
17. 12_express2.js
const express = require('express');
const app = express();
const port = 3000;
// 미들웨어 : 웹 서버 이외의 기능을 넣어줌
app.use((req, res) => {
res.writeHead('200', {'content-type':'text/html;charset=utf-8'});
res.end('<h2>익스프레스 서버에서 응답한 메시지 입니다.</h2>');
});
app.listen(port, () => {
console.log(`${port} 포트로 서버 실행중...`);
});
18. 13_express3.js
const express = require('express');
const app = express();
const port = 3000;
app.use((req, res) => {
console.log('첫번째 미들웨어 실행');
res.redirect('https://www.naver.com');
});
app.listen(port, () => {
console.log(`${port} 포트로 서버 실행중...`);
});
19. 14_express4.js
const express = require('express');
const app = express();
const port = 3000;
app.use((req, res) => {
console.log('첫번째 미들웨어 실행');
console.dir(req.header);
const userAgent = req.header('User-Agent'); // 사용자가 어떤 OS를 쓰는지, 브라우저를 쓰는지 등
// 사용자가 보내주는 정보를 얻어올 수 있다.
console.log(userAgent);
// http://localhost:3000/?userid=apple
const paramName = req.query.userid; // get 방식의 변수값을 가져옴
console.log(paramName);
res.writeHead(200, {'content-type' : 'text/html;charset=utf-8'});
res.write('<h2>익스프레스 서버에서 응답한 메시지입니다.</h2>');
res.write(`<p>User-Agent : ${userAgent}</p>`);
res.write(`<p>paramName : ${paramName}</p>`);
res.end();
});
app.listen(port, () => {
console.log(`${port} 포트로 서버 실행중...`)
});
20. http://localhost:3000/?userid=apple
1) PHP
$userid = $_GET['userid'];
2) node.js
const userid = req.query.userid;
** query : 클라이언트에서 GET 방식으로 전송한 요청 파라미터를 확인한다.
body : 클라이언트에서 POST 방식으로 전송한 요청 파라미터를 확인한다.
(단, post 방식을 통한 요청 파라미터를 확인하려면 body-parser와 같은 모듈을 사용해야 한다)
'웹_프론트_백엔드 > 프론트엔드' 카테고리의 다른 글
2021.02.27 (0) | 2021.02.27 |
---|---|
2021.02.21 (0) | 2021.02.21 |
2021.02.07 (0) | 2021.02.18 |
2021.02.06 (0) | 2021.02.06 |
2021.01.31 (0) | 2021.01.31 |