21
Node.js 介紹 Fin

Nodejs first class

Embed Size (px)

Citation preview

Page 1: Nodejs first class

Node.js 介紹Fin

Page 2: Nodejs first class

Node.js 是什麼

• Javascript 運⾏行平台

• 讓Javascript跳脫瀏覽器的限制

• 輕易建⽴立Web Server

• 事件驅動 (Event driven)

• ⾮非阻塞式 (Nonblocking)

Page 3: Nodejs first class

Why Node.js?

• 前後端語⾔言統⼀一,且能共⽤用模組• 其特性⾮非常適合即時網路服務• 本⾝身就可以是⼀一個HTTP伺服器

• 強⼤大的套件管理及開源社群

Page 4: Nodejs first class

Why not Node.js?

• ⾮非常新的技術,版本甚⾄至還沒1.0

• 對需要⼤大量CPU的⼯工作不拿⼿手 - 直譯式語⾔言

• library不如其他語⾔言來的多樣及完整(但在快速發展中)

Page 5: Nodejs first class

Node.js Dev Env Setup

• Install NVM

• Using NVM

Page 6: Nodejs first class

Install NVM

• Install NVMhttps://github.com/creationix/nvm/

• .bash_profile  加⼊入curl  https://raw.github.com/creationix/nvm/master/install.sh  |  sh

[[  -­‐s  /Users/$USERNAME/.nvm/nvm.sh  ]]  &&  .  /Users/$USERNAME/.nvm/nvm.sh  #  This  loads  NVM

Page 7: Nodejs first class

Using NVM#列出可安裝的node.js版本nvm  ls-­‐remote

#安裝某版本的nvmnvm  install  0.11

#列出本機端安裝的版本nvm  ls

#使⽤用某版本nvm  use  0.8

#設定預設版本nvm  alias  default  0.8

Page 8: Nodejs first class

Hello World!

• helloworld.js

• Run:$  node  helloworld.jsHello  World!

console.log(“Hello  World!”);

Page 9: Nodejs first class

Directory Structure

project  root/    config/    controllers/    doc/    models/    public/        js/        css/        img/    test/    views/    package.json    README.md

Page 10: Nodejs first class

Build a HTTP Server

#helloserver.js

#A  http  server  that  returns  ‘Hello  World’var  http  =  require('http');  http.createServer(function  (req,  res)  {        res.writeHead(200,  {'Content-­‐Type':  'text/plain'});        res.end('Hello  World\n');}).listen(8124,  "127.0.0.1");console.log('Server  running  at  http://127.0.0.1:8124/');

$  node  helloserver.jsServer  running  at  http://127.0.0.1:8124/

Page 12: Nodejs first class

Simplest Express Server

var  express  =  require('express');

var  app  =  express.createServer();

app.get('/',  function(req,  res)  {          res.send('This  is  an  Express  Server');});app.listen(8000);

Page 13: Nodejs first class

Message Board

/**  *  Module  dependencies.  */

var  express  =  require('express');

var  app  =  express();

//  Configuration

app.configure(function(){    app.set('views',  __dirname  +  '/views');    app.set('view  engine',  'jade');    app.use('/public',  express.static(__dirname  +  '/public'));});

https://github.com/finfin/MessageBoard

Page 14: Nodejs first class

//  Routesapp.get('/',  function(req,  res)  {    var  title  =  'Switter',            header  =  'Welcome  to  Switter';

   res.render('index',  {        'title':  title,        'header':  header,        'tweets':  tweets,    })})

var  tweets  =  [];app.get('/tweets',  function(req,res)  {    res.send(tweets);})

app.post('/send',  express.bodyParser(),  function(req,  res)  {    if  (req.body  &&  req.body.tweet)  {        tweets.push(req.body.tweet);        res.send({status:"ok",  message:"Tweet  received"});    }  else  {        //no  tweet?        res.send({status:"nok",  message:"No  tweet  received"});    }})

app.listen(8000);

Page 15: Nodejs first class

HTML Template - Jade

• 網⾴頁的呈現• 語法簡潔• http://jade-lang.com/

$  npm  install  jade

Page 16: Nodejs first class

Jade Templatedoctype  5html(lang="zh-­‐tw")   head     meta(charset="utf8")     link(rel='stylesheet',  href='/public/style.css')     title=  title   body     h1=  header     block  content

extends  layout

block  content   form(action="/send",  method="POST")     input(type="text",  length="140",  name="tweet")     input(type="submit",  value="發送")   each  tweet  in  tweets     p=  tweet

Page 17: Nodejs first class

• 套件越⽤用越多,要如何管理? >>> NPM!

• package.json

Package Management

{    "name":  "MessageBoard",    "version":  "0.0.1",    "dependencies":  {        "express":  "*",        "jade":  "*"    }}

#幫你安裝package.json裡⾯面所有的套件$  npm  install

Page 18: Nodejs first class

Improvementfunction  acceptsHtml(header)  {        var  accepts  =  header.split(',');        for(i=0;  i  <  accepts.length;  i++)  {                if  (accepts[i]  ===  'text/html')  {  return  true;  };          }        return  false;  }

app.post('/send',  express.bodyParser(),  function(req,  res)  {        if  (req.body  &&  req.body.tweet)  {                tweets.push(req.body.tweet);                if(acceptsHtml(req.headers['accept']))  {                          res.redirect('/',  302)                }  else  {                        res.send({status:"ok",  message:"Tweet  received"});                };        }  else  {                //no  tweet?                res.send({status:"nok",  message:"No  tweet  received"});        };});

Page 19: Nodejs first class

Result