node.js

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

var result = db.query("select * from T");
// use result
db.query("select * from T",
  function(result) {
    // use result
  }
);

์ด๋ฒคํŠธ ๋ฃจํ”„

event loop

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

์„œ๋ฒ„์‚ฌ์ด๋“œ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๊ฐœ๋ฐœํ™˜๊ฒฝ ์„ค์น˜

๋ชจ๋“ˆ ๋งŒ๋“ค๊ณ  ์ฐธ์กฐํ•˜๊ธฐ

ES6 setting

npm ์„ ํ†ตํ•œ ํ™•์žฅ

socket.io ๋ชจ๋“ˆ

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "express": "^4.14.0",
    "socket.io": "^4.1.2"
  }
}
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/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');
});
<!doctype html>
<html lang="ko">

<head>
  <title>Socket.IO chat</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    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 id="form" action="">
    <input id="input" autocomplete="off" /><button>Send</button>
  </form>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    var messages = document.getElementById('messages');
    var form = document.getElementById('form');
    var input = document.getElementById('input');

    form.addEventListener('submit', function (e) {
      e.preventDefault();
      if (input.value) {
        socket.emit('chat message', input.value);
        input.value = '';
      }
    });

    socket.on('chat message', function (msg) {
      var item = document.createElement('li');
      item.textContent = msg;
      messages.appendChild(item);
      window.scrollTo(0, document.body.scrollHeight);
    });
  </script>
</body>

</html>

์‹คํ–‰

npm i
node server.js

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}/`);
});

express.js

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

get

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

post

app.post('/', function (req, res) {
    res.send('Got a POST request')
})

put

app.put('/user', function (req, res) {
    res.send('Got a PUT request at /user')
})

delete

app.delete('/user', function (req, res) {
    res.send('Got a DELETE request at /user')
})

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.

app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...')
  next() // pass control to the next handler
})

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 debug

node debug myscript.js
x = 5;
setTimeout(() => {
  debugger;
  console.log('world');
}, 1000);
console.log('hello');

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

ref

What Else?
inflearn react api server -50% ํ• ์ธ์ฟ ํฐ: 15108-f2af1e086101 buy me a coffee