on
[Node.js] 이벤트 루프
[Node.js] 이벤트 루프
728x90
1) 이벤트 루프
- node.js는 서버가 실행되면 변수들을 초기화하고 함수를 선언하고 이벤트가 발생할 때까지 기다리게 된다.
- 이벤트가 감지되었을 때 call back함수를 호출한다.
- node.js 사이트 내 about 탭에 있는 코드 복사하여 붙여넣기
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}/`); });
- 이벤트 관련 메소드를 사용할 수 있는 EventEmitter 객체 생성하기
const events = require('events'); // 이벤트 관련 메소드를 사용할 수 있는 EventEmitter 객체를 생성 const eventEmitter = new events.EventEmitter(); const connectHandler = function connected(){ console.log('연결 성공'); eventEmitter.emit('data_received'); } eventEmitter.on('connection', connectHandler); eventEmitter.on('data_receive', () => { console.log('데이터 수신'); }); eventEmitter.emit('connection'); console.log('프로그램 종료');
2) 시스템 이벤트
exit
- 프로그램이 종료되거나 종료되는 시점을 알 수 있다.
// process 객체는 노드에서 항상 사용할 수 있는 객체 // exit는 process 객체 안에 포함 process.on('exit', () => { console.log('exit 이벤트 발생'); }); setTimeout( () => { console.log('프로그램을 종료합니다.'); process.exit; }, 3000);
3) http 모듈
- node.js에서 가장 기본적이고 중요한 서버 모듈이다.
- 이벤트가 감지되었을 때 call back함수를 호출한다.
- http 웹 서버를 생성하는 것과 관련된 모든 기능을 담당한다.
const http = require('http'); http.createServer((req,res) => { res.writeHead(200, {'content-type':'text/html'}); res.end(`http 모듈 테스트http 모듈 테스트`) }).listen(3000, () => { console.log('3000번 포트로 서버 실행중...'); });
4) 메소드
1. createServer( )
- server 객체를 생성한다.
2. writeHead( )
- 응답 header를 구성한다.
3. end( )
- 응답 body를 작성한다.
4. listen( )
- 서버를 실행하고 클라이언트를 기다린다.
5) MIME 형식
1. text/plain
- 일반적인 text 파일
728x90
from http://rinlab.tistory.com/138 by ccl(A) rewrite - 2021-08-07 18:26:18