Upload
chuo-han-chen
View
1.249
Download
0
Embed Size (px)
Citation preview
Node.js 介紹Fin
Node.js 是什麼
• Javascript 運⾏行平台
• 讓Javascript跳脫瀏覽器的限制
• 輕易建⽴立Web Server
• 事件驅動 (Event driven)
• ⾮非阻塞式 (Nonblocking)
Why Node.js?
• 前後端語⾔言統⼀一,且能共⽤用模組• 其特性⾮非常適合即時網路服務• 本⾝身就可以是⼀一個HTTP伺服器
• 強⼤大的套件管理及開源社群
Why not Node.js?
• ⾮非常新的技術,版本甚⾄至還沒1.0
• 對需要⼤大量CPU的⼯工作不拿⼿手 - 直譯式語⾔言
• library不如其他語⾔言來的多樣及完整(但在快速發展中)
Node.js Dev Env Setup
• Install NVM
• Using NVM
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
Using NVM#列出可安裝的node.js版本nvm ls-‐remote
#安裝某版本的nvmnvm install 0.11
#列出本機端安裝的版本nvm ls
#使⽤用某版本nvm use 0.8
#設定預設版本nvm alias default 0.8
Hello World!
• helloworld.js
• Run:$ node helloworld.jsHello World!
console.log(“Hello World!”);
Directory Structure
project root/ config/ controllers/ doc/ models/ public/ js/ css/ img/ test/ views/ package.json README.md
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/
Build a HTTP Server - Using Express
$ npm install [email protected] node_modules/express├── [email protected]├── [email protected]├── range-‐[email protected]├── cookie-‐[email protected]├── [email protected]├── buffer-‐[email protected]├── [email protected]├── [email protected]├── [email protected]├── [email protected]├── [email protected] ([email protected])└── [email protected] ([email protected], [email protected], [email protected])
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);
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
// 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);
HTML Template - Jade
• 網⾴頁的呈現• 語法簡潔• http://jade-lang.com/
$ npm install jade
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
• 套件越⽤用越多,要如何管理? >>> NPM!
• package.json
Package Management
{ "name": "MessageBoard", "version": "0.0.1", "dependencies": { "express": "*", "jade": "*" }}
#幫你安裝package.json裡⾯面所有的套件$ npm install
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"}); };});
Result
Resources
• http://nodejs.tw/
• http://www.nodebeginner.org/index-zh-tw.html#javascript-and-nodejs
• https://www.facebook.com/groups/node.js.tw
• http://book.nodejs.tw/index.html
About US
• http://www.zencher.com/
• 課程:雲端服務開發http://www.zencher.com/#course/course-cloudapp
• https://www.facebook.com/thingsaboutwebdev