Nodejs

 

 

인프런 :  https://www.inflearn.com/course/web2-node-js#

 

생활 코딩 :  https://opentutorials.org/module/3549

 

 

소스 :  https://github.com/braverokmc79/WEB2-Nodejs

 

Node.js

 

1.수업소개

 

2.수업의 목적

 

 

 

Node.js 설치

 

3.설치

 

 

4.Windows

 

https://nodejs.org/ko/

 


 

 

 

5.MacOS

 

6.Linux & Codeanywhere

 

https://codeanywhere.com/

 

프로그래밍 언어를 웹에서 실행하고 공유도 가능한 사이트

https://blog.gaerae.com/2015/06/website-run-execute-code-online.html

 

https://wandbox.org/

http://ideone.com

https://repl.it

 

 

 

JavaScript의 기본문법 & Node.js의 주요 기능 & 웹앱

 

7.공부방법

 

 

8.웹서버 만들기

 

 

강좌 : https://opentutorials.org/module/3549/21032

 

소스 :  https://github.com/web-n/web1_html_internet

 

 

 

9.Data type - Number

 

Number.js

console.log(1 + 1);
console.log(4 - 1);
console.log(2 * 2);
console.log(10 / 2);

 

 

 

 

 

10.Data type - String

 

 

 

 

11.변수의 형식

var a = 1;
console.log(a);
a = 2;
console.log(a);
//1 = 2;

 

 

 

12.변수의 활용

 

 

 

 

13.Template Literal

 

ES6 이전엔 표현식을 다음과 같이 일반 문자열 안에 집어넣었습니다.

var a = 20;
var b = 8;
var c = "자바스크립트";
var str = "저는 " + (a + b) + "살이고 " + c + "를 좋아합니다.";
console.log(str);   //저는 28살이고 자바스크립트를 좋아합니다.

템플릿 리터럴에서는 아래와 같이 $와 중괄호{}를 사용하여 표현식을 표기할 수 있습니다.

let a = 20;
let b = 8;
let c = "자바스크립트";
let str = `저는 ${a+b}살이고 ${c}를 좋아합니다.`;
console.log(str);   //저는 28살이고 자바스크립트를 좋아합니다.

위 처럼 + 연산자로 문자열을 연결해주는 것보다 가독성이 더 좋습니다.

 

 

 

 

 

14.URL의 이해

 

 

 

 

15.URL을 통해서 입력된 값 사용하기

 

var http = require('http');
var fs = require('fs');
var url = require("url");

var app = http.createServer(function (request, response) {
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    console.log(queryData.id);

    if (_url == '/') {
        _url = '/index.html';
    }
    if (_url == '/favicon.ico') {
        response.writeHead(404);
        response.end();
        return;
    }
    response.writeHead(200);
    //response.end(fs.readFileSync(__dirname + url));
    response.end(queryData.id);

});
app.listen(3000);

 

 

 

 

 

16.동적인 웹페이지 만들기

 

 

 

 

17.Node.js의 파일 읽기 기능

 

fileboard.js

var fs = require("fs");
fs.readFile('sample.txt', 'utf8', function (err, data) {
    console.log(data);
});

 

 

 

 

 

18.파일을 이용해 본문 구현

 

var http = require('http');
var fs = require('fs');
var url = require("url");

var app = http.createServer(function (request, response) {
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  var title = queryData.id;

  if (_url == '/') {
    _url = '/index.html';
  }
  if (_url == '/favicon.ico') {
    response.writeHead(404);
    response.end();
    return;
  }
  response.writeHead(200);
  fs.readFile(`data/${queryData.id}`, 'utf-8', function (err, data) {
    console.log(data);
    var template = `
        <!doctype html>
<html>
<head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.html">WEB</a></h1>
  <ol>
    <li><a href="?id=HTML">HTML</a></li>
    <li><a href="?id=CSS">CSS</a></li>
    <li><a href="?id=JavaScript">JavaScript</a></li>
  </ol>
  <h2>${title}</h2>
  <p><a href="https://www.w3.org/TR/html5/" target="_blank" title="html5 speicification">
  Hypertext Markup Language (HTML)</a> is the standard markup language for <strong>creating <u>web</u> pages</strong> and web applications.Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
  <img src="coding.jpg" width="100%">
  </p><p style="margin-top:45px;">${data}
  </p>
</body>
</html>
        
        `;

    response.end(template);
  });


});
app.listen(3000);

 

 

 

 

19.Boolean

 

 

 

 

20.비교연산자

 

 

 

 

21.제어문

 

 

 

 

 

22.조건문

 

 

 

23.Node JS콘솔에서의 입력값

.

 

 

 

 

24.Not found 구현

 

var http = require('http');
var fs = require('fs');
var url = require("url");

var app = http.createServer(function (request, response) {
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  var title = queryData.id;
  var pathname = url.parse(_url, true).pathname;

  if (pathname === '/') {
    response.writeHead(200);
    fs.readFile(`data/${queryData.id}`, 'utf-8', function (err, data) {
      console.log(data);
      var template = `
                  <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="index.html">WEB</a></h1>
            <ol>
              <li><a href="?id=HTML">HTML</a></li>
              <li><a href="?id=CSS">CSS</a></li>
              <li><a href="?id=JavaScript">JavaScript</a></li>
            </ol>
            <h2>${title}</h2>
            <p><a href="https://www.w3.org/TR/html5/" target="_blank" title="html5 speicification">
            Hypertext Markup Language (HTML)</a> is the standard markup language for <strong>creating <u>web</u> pages</strong> and web applications.Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
            <img src="coding.jpg" width="100%">
            </p><p style="margin-top:45px;">${data}
            </p>
          </body>
          </html>
                  
                  `;

      response.end(template);
    });

  } else {
    response.writeHead(400);
    response.end("Not found");
  }



});
app.listen(3000);

 

 

 

 

 

25.홈페이지 구현

 

var http = require('http');
var fs = require('fs');
var url = require("url");

var app = http.createServer(function (request, response) {
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  var title = queryData.id;
  var pathname = url.parse(_url, true).pathname;

  if (pathname === '/') {


    fs.readFile(`data/${queryData.id}`, 'utf-8', function (err, description) {

      if (queryData.id === undefined) {
        title = "Welcome";
        description = "Hello, Node.js";
      }

      var template = `
                  <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="index.html">WEB</a></h1>
            <ol>
              <li><a href="?id=HTML">HTML</a></li>
              <li><a href="?id=CSS">CSS</a></li>
              <li><a href="?id=JavaScript">JavaScript</a></li>
            </ol>
            <h2>${title}</h2>
            <p><a href="https://www.w3.org/TR/html5/" target="_blank" title="html5 speicification">
            Hypertext Markup Language (HTML)</a> is the standard markup language for <strong>creating <u>web</u> pages</strong> and web applications.Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
            <img src="coding.jpg" width="100%">
            </p><p style="margin-top:45px;">${description}
            </p>
          </body>
          </html>                  
                  `;
      response.writeHead(200);
      response.end(template);


    });

  } else {
    response.writeHead(400);
    response.end("Not found");
  }



});
app.listen(3000);

 

 

 

 

 

26.반복문

 

 

 

 

27.배열

 

 

28.배열과 반복문

 

 

 

29.Node.js에서 파일목록 알아내기

 

var testFolder = '../data';
var fs = require('fs');

fs.readdir(testFolder, function (err, fileList) {
    console.log(fileList);
})

 

 

 

 

 

30.글목록 출력하기

 

app.js

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

const app = http.createServer(function (request, response) {
  const _url = request.url;
  const queryData = url.parse(_url, true).query;
  const pathname = url.parse(_url, true).pathname;
  let title = queryData.id;
  let menuList = "";



  if (pathname === '/') {

    //readdirSync 동기식처리
    let filelist = fs.readdirSync('../data');
    filelist.forEach(item => {
      menuList += `
                <li><a href="?id=${item}">${item}</a></li>
            `;
    })


    fs.readFile(`../data/${queryData.id}`, 'utf-8', function (err, description) {

      if (queryData.id === undefined) {
        title = "Welcome";
        description = "Hello, Node.js";
      }
      var template = `
                  <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            <ol>
              ${menuList}
            </ol>
            <h2>${title}</h2>
            <p><a href="https://www.w3.org/TR/html5/" target="_blank" title="html5 speicification">
            Hypertext Markup Language (HTML)</a> is the standard markup language for <strong>creating <u>web</u> pages</strong> and web applications.Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
            <img src="coding.jpg" width="100%">
            </p><p style="margin-top:45px;">${description}
            </p>
          </body>
          </html>                  
                  `;
      response.writeHead(200);
      response.end(template);


    });

  } else {
    response.writeHead(400);
    response.end("Not found");
  }



});
app.listen(3000);

 

 

 

 

 

31.함수의 기본 문법

 

 

 

 

32.함수의 입력

 

 

 

 

 

33.함수의 출력

 

 

 

 

34.함수를 이용해서 정리

 

 

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



function templateHTML(title, menuList, body) {
  return `
    <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            <ol>${menuList}</ol>
            ${body}
    </body>
    </html>       
  `;
}

function templateList(filelist) {
  let menuList = "";
  filelist.forEach(item => {
    menuList += `<li><a href="?id=${item}">${item}</a></li>`;
  })
  return menuList;
}

const app = http.createServer(function (request, response) {
  const _url = request.url;
  const queryData = url.parse(_url, true).query;
  const pathname = url.parse(_url, true).pathname;
  let title = queryData.id;


  if (pathname === '/') {

    //readdirSync 동기식처리 파일 목록 읽기
    const filelist = fs.readdirSync('../data');
    let menuList = templateList(filelist);

    fs.readFile(`../data/${queryData.id}`, 'utf-8', function (err, description) {
      if (queryData.id === undefined) {
        title = "Welcome";
        description = "Hello, Node.js";
      }

      const template = templateHTML(title, menuList, `<h2>${title}</h2>${description}`);
      response.writeHead(200);
      response.end(template);
    });

  } else {
    response.writeHead(400);
    response.end("Not found");
  }

});
app.listen(3000);

 

 

 

 

 

 

수업의 정상

 

 

35.수업의 정상

 

 

 

 

 

36.Nodejs에서 동기와 비동기 (1/2)

 

 

 

 

37.Nodejs에서 동기와 비동기 (2/2)

 

const fs = require("fs");


//readFileSync
// console.log('A');
// const result = fs.readFileSync('sample.txt', 'utf8');
// console.log(result);
// console.log('C');


console.log('A');
fs.readFile('sample.txt', 'utf8', function (err, result) {
    console.log(result);
});
console.log('C');

 

 

 

 

 

 

38.callback

 

// function a() {
//     console.log('A');
// }
var a = function () {
    console.log('A');
}

function b() {
    console.log('B');
}


function slowfunc(callback) {
    callback();
}


slowfunc(a);

 

 

 

 

 

39.패키지 매니저와 PM2

 

설치

$ npm install pm2@latest -g
# or
$ yarn global add pm2	

앱 시작

$ pm2 start *.js # default
$ pm2 start *.sh / *.py / binary-file... # 여러가지 포맷의 파일 지원
  • 기본 명령어로 pm2를 이용해 앱을 실행한다면 fork모드로 설정되어서, 단일 인스턴스는 단일 스레드로 실행되는 Node의 특징을 따르게 된다.
  • pm2 에서는 Cluster 모드도 사용가능하다. 관련하여 알고 싶다면 여기를 참조해보자!

CLI 로 전달가능한 옵션들

# 앱 이름 지정
--name <app_name>

# 항상 모니터링하다가, 관련해서 파일이 변경되면 앱 재시작
--watch

# watch옵션시에 특정 폴더 경로는 무시해야할 때 (log 폴더 지정하면...이거 이용해서 제거해주자. 아니면 무한 재실행을 볼 수 있다.)
--watch --ignore-watch="[dir]/*"

# 앱이 리로드 될때 최대의 메모리 지정
--max-memory-restart <200MB>

# 로그 파일 패스 지정
--log <log_path>

# 스크립트에 추가 인수 전달
-- arg1 arg2 arg3

# 재시작할때의 딜레이 지정
--restart-delay <delay in ms>

# 로그 남길때 프리픽스로 시간 지정
--time

# 재시작 불가하도록 설정
--no-autorestart

# 주기적으로 강제 재시작이 필요할때 설정 (cron)
--cron <cron_pattern>

# Attach to application log
--no-daemon

앱 관리

$ pm2 restart app_name # 프로세스 종료하고 재시작
$ pm2 reload app_name # 프로세스 종료없이 재시작
$ pm2 stop app_name # 프로세스 스탑
$ pm2 delete app_name # 프로세스 삭제
  • app_name 대신에 all, id를 넣을 수 있다.
    • all : 모든 프로세스 대상
    • id : 특정 프로세스 대상

모니터링

$ pm2 status
$ pm2 ls
$ pm2 list
$ pm2 prettylist # json 
$ pm2 monit

해당 명령어를 치면 현재 실행중인 프로세스에 대해서 모니터링이 진행가능하다.

다른 명령어들과 다르게, monit 명령어는 실시간 상태를 확인할 수 있는 모니터링 창을 열어준다.

Scale

Scale 관리

# 프로세스 4개 늘리기
$ pm2 scale app +4
# 프로세스 4개 줄이기
$ pm2 scale app -4
# 프로세스 4개로 설정하기
$ pm2 scale app 4

Log

pm2 에서 진행중인 프로세스에 대해서 로그를 확인하고 싶다면 다음 명령어를 사용하면 된다.

# all
$ pm2 logs

# specific process log
$ pm2 logs [process name | process id]

# lines option
$ pm2 logs --lines 200

Log Rotate

pm2에서 Log Rotate 관리를 위해서는 pm2-logrotate 플러그인을 설치하면 됩니다.

# npm으로 설치하는 것이 아닌 pm2로 설치
$ pm2 install pm2-logrotate

# 옵션 설정은 다음과 같이 설정
$ pm2 set pm2-logrotate:<option> <value>

Options

  • max_size: 로그 파일 사이즈 제한 크기 (기본값은 10M)
  • retain: 로그 파일을 최대 몇개까지 가지고 있을 것인지 설정 (기본값은 30개)
  • compress: 로그 파일을 gzip으로 압축할 것인지 여부 (기본값은 false)
  • dateFormat: 로그 파일 날짜 폼새 (기본값은 YYYY-MM-DD_HH-mm-ss)
  • workerInterval: 로그 파일 사이즈를 확인하는 1초마다의 회수 (기본값 초당 30회)
  • rotateInterval: cron job (기본값은 '0 0 * * *')

Update

# update pm2 
$ npm install pm2@latest -g
$ pm2 update
  • 두 명령어 모두 실행해야한다.

 

참고

https://pm2.keymetrics.io/docs/usage/quick-start/
https://velog.io/@altmshfkgudtjr/PM2-Node.js-%EB%AC%B4%EC%A4%91%EB%8B%A8-%EC%84%9C%EB%B9%84%EC%8A%A4

 

 

 

 

 

 

40.HTML - Form

 

 

 

 

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  라이트

잠 못 드는 사람에게는 밤이 길고 피곤한 사람에게는 길이 멀다. 바른 법을 모르는 어리석은 자에게는 삶과 죽음의 길 또한 길고 멀다. -법구경

댓글 ( 4)

댓글 남기기

작성

Nodejs 목록    more