node.js 알아보기

1

node.js

목록 보기
4/5
post-thumbnail

What is Node.js?

  • 노드는 v8엔진으로 만들어진 자바스트립트 런타임이다.
    v8 = 자바스크스립트를 기계어로 컴파일 해준다!
    런타임 = 프로그래밍 언어가 구동되고 있는 환경

즉 자바스크립트를 컴파일 해주는 엔진으로 빌드 된 자바스크립트가 구동중인 환경이다

  • 이벤트 기반 및 논블로킹 I/O
    이벤트 = 유저의 버튼 클릭이나 네트워크에 리소스를 요청 하는 것 등
    블로킹 = 다음 함수의 실행이 현재 함수의 종료 이후에 이루어 지는 것
    논블로킹 = 다음 함수의 실행이 현재 함수의 종료를 기다리지 않음
    I/O = input을 주면 OutPut을 반환하는 모델

즉 유저의 클릭이나 네트워크에 리소스를 요청하는 이벤트가 논블로킹으로 이루어지는 Input Output model

  • javascript 를 컴파일 하여 구동하고
  • 이벤트 기반의 non bloccking모델로 속도가 빠르다

Node core modules

node와 함께 번들링 되어 있는 모듈 require방식으로 사용 할 수 있다.
fs,http,url,path등이 있다.

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

fs.readFile('./something.json',(err,data)=>{
    console.log(data);
})

http.get('http://localhost:5000/api',(res)=>{
    console.log(res)
})

NPM

세계에서 가장 큰 오픈소스 라이브러리 생태계 중 하나
package.json에 그 정보들이 모두 담겨있다.

Package.json

  • npm을 활용하기 위한 정보들이 모여 있는 파일!
  • project 전반에 관한 정보가 들어있다.
  • dev- dependency에는 production과 관계없는 개발만을 위한 dependency가 적혀있다.
  • dependency 에는 production과 관련있는 dependency가 적혀있다.

npm을 쓸때는 --save옵션을 줘야한다.
npm install을 하면 package.json에 있는 dependecy를 바탕으로 설치 한다. --save를 하지 않으면 dependency에 등록 되지 않아 npm insatall을 하여도 다운받아 지지 않는다.

HTTP

Node.js HTTP 처리 과정을 이해해보자
EventEmitters 와 Streams 에 어느정도 익숙해 져야 합니다.

EventEmitter는 Node.JS에 내장되어 있는 일종의 옵저버 패턴 구현이다. node 뿐만 아니라 대부분의 프레임워크나 라이브러리에서 이 구현을 쓰거나 유사한 구현을 활용하고 있는 경우가 많다.

간단한 서버 소스로 대략적인 서버를 알아봅시다. !

server.js

const http = require('http'); //node 내장 모듈 불러옴
const PORT = 5000; 
const ip = 'localhost';
const server = http.createServer((request, response) => {
  if (request.method === 'OPTIONS') {//options가 200통과를 받아야 다음 값을 post할 수 있다. 
    response.writeHead(200, defaultCorsHeader);//응답 헤더를 작성합니다.
    response.end()//응답 본문을 작성합니다.
  }
  //   request 객체의 속성
  //  - method : 클라이언트 요청 방식을 나타냅니다.
  //  - url : 클라이언트가 요청한 URL을 나타냅니다.
  if (request.method === 'POST' && request.url === '/upper') { // 메서드가 post이고 url가 /upper이면 
    let body = [];
    request.on('data', (chunk) => {
    body.push(chunk);
    }).on('end', () => {
      body = Buffer.concat(body).toString().toUpperCase();//데이터를 배열에 수집하여 문자열로 만든 후 대문자로 변환 
      response.writeHead(200, defaultCorsHeader);//정상코드200
      response.end(body);
    });
 } else if (request.method === 'POST' && request.url === '/lower') {
    let body = [];
    request.on('data', (chunk) => {
      body.push(chunk);
    }).on('end', () => {
      body = Buffer.concat(body).toString().toLowerCase();
      response.writeHead(200, defaultCorsHeader);
      response.end(body);
    });
   } else {// 에러일때 
    request.on('error', (err) => {
      response.writeHead(400, defaultCorsHeader);//400코드 뿌리기
      console.error('err')
    })
  }
  });
server.listen(PORT, ip, () => { //listen(port[, callback]) : 서버를 실행합니다.
  console.log(`http server listen on ${ip}:${PORT}`);
});
const defaultCorsHeader = {//cors정책
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Accept',
  'Access-Control-Max-Age': 10
};

client.js

class App {//App클래스 생성
  init() {//처음 시작
    document//upper버튼 클릭시
      .querySelector('#to-upper-case')
      .addEventListener('click', this.toUpperCase.bind(this));
    document//lower버튼 클릭시
      .querySelector('#to-lower-case')
      .addEventListener('click', this.toLowerCase.bind(this));
  }
  post(path, body) {//서버에서 가져오기
    fetch(`http://localhost:5000/${path}`, {
      method: 'POST',
      body: JSON.stringify(body),
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(res => res.json())
      .then(res => {
        this.render(res);
      });
  }
  //메서드
  toLowerCase() {
    const text = document.querySelector('.input-text').value;
    this.post('lower', text);//라우팅 lower넘기고 text값 넘기기 
  }
  toUpperCase() {
    const text = document.querySelector('.input-text').value;
    this.post('upper', text);
  }
  render(response) {
    const resultWrapper = document.querySelector('#response-wrapper');
    document.querySelector('.input-text').value = '';
    resultWrapper.innerHTML = response;
  }
}
const app = new App();//인스턴스생성
app.init();//init실행
profile
👩🏻‍💻항상발전하자 🔥

0개의 댓글