node.js

[toc]

JS Warm Up

설치

node.js 개요

Node.js® is a platform
built on Chrome's JavaScript runtime
for easily building fast, scalable network applications.
Node.js uses an event-driven, non-blocking I/O model
that makes it lightweight and efficient, perfect
for data-intensive real-time applications
that run across distributed devices.

특징

장점

단점

비동기 프로그래밍

blocking, non-blocking

from: https://www.dropbox.com/s/o9g4m7tug3yt1xx/jsconf2009-nodejs.pdf?dl=0

이벤트 루프

event loop

from blog.udemy.com/learn-node-js/

안티 패턴

“헤이, probablyExpensiveFunction(), 니 일을 해줘.
하지만 나 Single Node.js 쓰레드는 네가 끝낼 때까지 여기서 기다리지 않을거야.
네 아래에 있는 코드 라인을 계속 실행할거야.
그러니 여기 이 callbackFunction()을 가져가서
네가 너의 비싼 일을 모두 끝냈을 때 호출해 주겠니?
고마워!”

from: http://www.nodebeginner.org/index-kr.html#how-to-not-do-it

서버사이드 자바스크립트 개발환경 설치

모듈 만들고 참조하기

npm 을 통한 확장

socket.io 모듈

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>

<script>
  var socket = io();
  $('form').submit(function(){
    socket.emit('chat message', $('#m').val());
    $('#m').val('');
    return false;
  });
  socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });
</script>
  </body>
</html>
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "express": "^4.14.0",
    "socket.io": "^1.5.0"
  }
}

expressjs 웹 프레임워크

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\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
var express = require('express')
var app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

express-generator

basic routing

Routing

methods

get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, propfind, proppatch, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch, search, connect.

Route Parameters

Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
app.get('/users/:userId/books/:bookId', function (req, res) {
  res.send(req.params)
})

MairaDB 설치

MongoDB + node.js

node cluster 시작하기

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}

node.js clustering with PM2

JavaScript Code Quality

node.js PaaS 활용 - heroku

디버깅

개요

node.js debug

email

Test Frameworks

서버 모니터링

$ cd ~/dev/mongodb/bin
$ mkdir -p ~/data/db
$ ./mongod --dbpath=/Users/kenu/data/db

$ cd ~/dev/mongodb/bin
$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use uptime
switched to db uptime
> db.addUser('uptime', 'okpass');
{
    "user" : "uptime",
    "readOnly" : false,
    "pwd" : "fdc9e10c8f90fac0c9fe786f28cc04f4",
    "_id" : ObjectId("5577b97a62555c0332f63e6f")
}
> exit


$ git clone git://github.com/fzaninotto/uptime.git
$ cd uptime
$ npm install

영상

  1. 개요, 설치 https://www.youtube.com/watch?v=Z8cOppJwOeU
  2. socket.io, express.js https://www.youtube.com/watch?v=YWaoLdoqSWE
  3. express.js basic routing https://www.youtube.com/watch?v=KOtEZ0j0cic
  4. express.js api https://www.youtube.com/watch?v=-nHp0D4n4Do
  5. express.js resources https://www.youtube.com/watch?v=4bIIX07vN-8
  6. mariadb 연결(Windows) https://www.youtube.com/watch?v=VTBACySodEc
  7. node cluster https://www.youtube.com/watch?v=2v7oRhit8lQ
  8. node debugging https://www.youtube.com/watch?v=TaMYKdcBIGA
  9. Code Quality https://www.youtube.com/watch?v=1931C8MAvdM
  10. jade 2 ejs template https://www.youtube.com/watch?v=IeOoN1LZ4f0
  11. Express + MariaDB(mysql) Web App https://www.youtube.com/watch?v=UocHh8604Lc
  12. Async, Nested SQL https://www.youtube.com/watch?v=PJ7fQnDLmWg
  13. email

참고

What Else?