menu

주요 기본 모듈1

node 주요 기본모듈

별도의 설치 과정 없이 사용할 수 있는 모듈로 Node.js와 함께 설치된다.

프로세스 환경 os, process, cluster

파일과 경로, URL fs, path, URL, queryString, stream

네트워크 모듈 http, https, net, dgram, dns

전역객체 - global 모듈에 속하는 객체와 함수로 모듈 로딩 과정없이 사용할 수 있다.
console - console을 으용하여 콘솔화면에 내용을 출력할 뿐만 아니라 실행 시간을 측정할 수 있다.
util - 유틸리티 모듈을 이용해서 형식 문자열을 작성할 수 있다. 그리고 클래스 간에 상속 관계를 만들 수 있다.
event - 이벤트를 다루는 EventEmitter의 특징과 이벤트를 다뤘으며 유틸리티 모듈의 상속을 이용해서 커스텀 이벤트로 다룰 수 있다.
timeout - 타이머 함수인 setTimeout()이나 setInterval() 함수를 이용해서 일정 시간 뒤에 동작하거나 주기적으로 동작하는 기능을 작성할 수 있다.
Buffer
require
__filename
__dirname
module
export


console Hello World

console.log('hello World')

웹 응답 Hello World

const http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, { 'Content-type': 'text/html' });
    response.end('<h1>Hello World</h1>')
}).listen(3000);

노드를 공부하는 사람들은 대부분 http 통신을 하는 서버를 만들고 그 위해서 동작하는 어플리케이션을 만들기 위해 학습을 할것이다.(물론 예외는 있다)
이때 사용하는 모듈이 http 모듈이며 http 모듈로 인해 노드는 쉽게 웹서버를 만들수 있다.

직접 응답

const http = require('http'); 
// http 자원을 준비한다 

http.createServer((req, res) => {
    console.log('응답완료')
    // 서버를 만든다 
    // 요청은 req(request)에 바인딩 되며
    // 응답은 res(response)에 바인딩 된다.
    res.end('<h1>Hello Node World</h1>')
    // 응답으로 html을 리턴한다
}).listen(8888, () => {
    console.log('서버 동작중...');
});

파일 응답

index.js

const http = require('http'); 
const fs = require('fs');
// 파일스트림 자원을 준비한다.

http.createServer((req, res) => {
    fs.readFile('./index.html', (err, data) => {
        // .(현재폴더)에서 index.html을 찾는다.
        // data에 바인딩 된다.
        if (err) {
            console.error(err)
        }
        res.end(data);
        // 응답으로 파일스트림으로 준비한 data를 리턴한다
    });
}).listen(8888, () => {
    console.log('8888 서버 동작중...');
});

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <h1>hello Node World!!!!!!!!!!</h1>
</body>

</html>

process - 어플리케이션 실행정보 객체

  • property
    • env : 애플리케이션 실행환경 ()
    • version : Node.js 버전
    • arch, platform : CPU와 플랫폼 정보
    • argv : 실행 명령 파라미터
      (node helloworld.js 3,5 시 process argv로 꺼내서 사용가능 var i = process.argv[2])
  • event
    • exit : 애플리케이션 종료 이벤트
    • beforeExit : 종료되기 전에 발생하는 이벤트
    • uncaughException : 예외 처리되지 않은 예외 이벤트
  • function
    • exit : 애플리케이션 종료
    • nextTrick : 이벤트 루프 내 동작을 모두 실행 후 콜백 실행

CODE

console.log(process.env)
console.log(process.version)
console.log(process.arch)
console.log(process.platform)

console - 콘솔(터미널) 출력 및 파일저장 또는 실행시간 측정 관련 객체
(로깅을 만들수 있다.)

  • loging function (level)
    • console.log()
    • console.warn()
    • console.error()
    • console.inf%o()
  • console 출력시 주의할점
    객체형 타입(object)은 console.log(‘var’, obj)처럼 사용해야 잘보인다 console.log(‘var’+ obj)를 넣으면 object object 나온다

CODE

console.time('TIMER');  // 시작시간 
var sum = 0;
for (var i = 0; i < 10; i++) {
    sum += i;
}
console.log('sum : ' + sum)
console.timeEnd('TIMER') // 종료시간

console.log("hello")
console.warn("hello")
console.error("hello")
console.info("hello")

util
유틸리티 모듈을 이용해서 형식 문자열을 작성할 수 있다. 그리고 클래스 간에 상속 관계를 만들 수 있다.

util 사용시 require를 이용해서 import 후 사용한다
function
- util.format(format[,%s, %d]) (printf와 비슷하다)
- util.inherits(child,parent) (상속 기능)

var util = require('util')

var str1 = util.format('%d + %d = %d', 1, 2, (1 + 2));
console.log(str1)
var str2 = util.format('%s  %s ', 'hello', 'world!');
console.log(str2)

// inherits  상속 
function parent() { }

parent.prototype.sayHello = function () {
    console.log('hello world, from parent class!')
}

var obj = new parent();
obj.sayHello();

function child() { }

util.inherits(child, parent)

var ojb2 = new child();
ojb2.sayHello();

Event
Event란?
이벤트(event)는 어떤 사건 의미한다. 브라우저에서의 사건이란 사용자가 특정 액션(행동)을 했을때 같은을 의미한다. >http://webclub.tistory.com/340

  • node에서 이벤트란?
    • 클라이언트의 접속 요청
    • 소켓에 데이터 도착
    • 파일 오픈/읽기 완료
  • 이벤트 처리
    • 비동기 처리
    • 리스너 함수

EventEmitter

  • ReadLine module
    • class : interface
      • rl.close()
      • rl.pause()
    • events
      • event:’close’
      • event:’line’
      • event:’pause’
      • event:’resume’
      • event:’SIGCONT’
      • event:’SIGINT’

이벤트 리스너란?
이벤트에 대응되는 함수이다.

이벤트 핸드로는 개수는 기본 10가지인데 아래의 함수를 이용하면 변경 가능하다
emitter.setMaxListeners(n)
emitter.getMaxListeners(n)

리스너 다루기
emitter.addListener(event, listner) (이거 많이 봤다…)
emitter.on(event, listner) (이벤트 시마다 동작하는 함수이다.)
emitter.once(event, listner) (이벤트를 한번만 동작할 시킬때 사용한다)

커스텀 이벤트 (이벤트객체에만 사용 가능)

var customEvent = new event.EventEmitter();        //custom 이벤트를 준비

customEvent.on('tick',function() {
console.log('custom event test')
});

customEvent.emit('tick')

// 커스텀 이벤트, 상속 

var Person = function(){};

var util = require('util')
var EventEmitter = require('events').EventEmitter;
util.inherits(Person, EventEmitter)

var p = new Person();
p.on('howAreYou', function(){
console.log('custom event inherit)
});

p.emit('howAreYou)


function test() { }
setTimeout(test, 5000)

process.on('exit', function () { 
//exit는 프로그래밍 종료될때 실행할수있도록 준비한다. 
console.log('Emitter on program exit')
//지속적으로 동작한다.  
});

process.once('exit', function () {
    console.log('Emitter once program exit')
     //한번만 동작한다.
});

emitter.removeListener(event, listener) 
// 이벤트 삭제 
emitter.removeAllListener(event, listener) 
// 모든 이벤트 삭제

process.on('uncaughtException', function (code) { 
    // 이벤트로 예외처리도 가능하다
    console.log('uncaughtException')
});