SlideShare a Scribd company logo
1 of 21
Download to read offline
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 NVM
https://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
#安裝某版本的nvm
nvm	
  install	
  0.11
#列出本機端安裝的版本
nvm	
  ls
#使⽤用某版本
nvm	
  use	
  0.8
#設定預設版本
nvm	
  alias	
  default	
  0.8
Hello World!
• helloworld.js
• Run:
$	
  node	
  helloworld.js
Hello	
  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	
  Worldn');
}).listen(8124,	
  "127.0.0.1");
console.log('Server	
  running	
  at	
  http://127.0.0.1:8124/');
$	
  node	
  helloserver.js
Server	
  running	
  at	
  http://127.0.0.1:8124/
Build a HTTP Server -
Using Express
$	
  npm	
  install	
  express
express@3.2.3	
  node_modules/express
├──	
  methods@0.0.1
├──	
  fresh@0.1.0
├──	
  range-­‐parser@0.0.4
├──	
  cookie-­‐signature@1.0.1
├──	
  qs@0.6.4
├──	
  buffer-­‐crc32@0.2.1
├──	
  cookie@0.0.5
├──	
  debug@0.7.2
├──	
  commander@0.6.1
├──	
  mkdirp@0.3.4
├──	
  send@0.1.0	
  (mime@1.2.6)
└──	
  connect@2.7.9	
  (pause@0.0.1,	
  bytes@0.2.0,	
  formidable@1.0.13)
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
//	
  Routes
app.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 Template
doctype	
  5
html(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
Improvement
function	
  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

More Related Content

What's hot

What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012
D
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS Intro
Ngoc Dao
 

What's hot (20)

What is nodejs
What is nodejsWhat is nodejs
What is nodejs
 
How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0
 
Write php deploy everywhere
Write php deploy everywhereWrite php deploy everywhere
Write php deploy everywhere
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
Microservice Teststrategie mit Symfony2
Microservice Teststrategie mit Symfony2Microservice Teststrategie mit Symfony2
Microservice Teststrategie mit Symfony2
 
Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8
 
#OktoCampus - Workshop : An introduction to Ansible
#OktoCampus - Workshop : An introduction to Ansible#OktoCampus - Workshop : An introduction to Ansible
#OktoCampus - Workshop : An introduction to Ansible
 
Automating OSD and Post-OSD Configuration with Powershell and Orchestrator
Automating OSD and Post-OSD Configuration with Powershell and OrchestratorAutomating OSD and Post-OSD Configuration with Powershell and Orchestrator
Automating OSD and Post-OSD Configuration with Powershell and Orchestrator
 
What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012
 
Getting Started with Ansible
Getting Started with AnsibleGetting Started with Ansible
Getting Started with Ansible
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
 
Application Layer in PHP
Application Layer in PHPApplication Layer in PHP
Application Layer in PHP
 
[Spring Camp 2013] Java Configuration 없인 못살아!
[Spring Camp 2013] Java Configuration 없인 못살아![Spring Camp 2013] Java Configuration 없인 못살아!
[Spring Camp 2013] Java Configuration 없인 못살아!
 
Celery
CeleryCelery
Celery
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS Intro
 
Network Automation: Ansible 102
Network Automation: Ansible 102Network Automation: Ansible 102
Network Automation: Ansible 102
 
Cloud meets Fog & Puppet A Story of Version Controlled Infrastructure
Cloud meets Fog & Puppet A Story of Version Controlled InfrastructureCloud meets Fog & Puppet A Story of Version Controlled Infrastructure
Cloud meets Fog & Puppet A Story of Version Controlled Infrastructure
 
Angular 1 + es6
Angular 1 + es6Angular 1 + es6
Angular 1 + es6
 
A Introduction of Packer
A Introduction of PackerA Introduction of Packer
A Introduction of Packer
 

Viewers also liked

[INSIGHT OUT 2011] A23 database io performance measuring planning(alex)
[INSIGHT OUT 2011] A23 database io performance measuring planning(alex)[INSIGHT OUT 2011] A23 database io performance measuring planning(alex)
[INSIGHT OUT 2011] A23 database io performance measuring planning(alex)
Insight Technology, Inc.
 
Web technologies for desktop development
Web technologies for desktop developmentWeb technologies for desktop development
Web technologies for desktop development
Darko Kukovec
 
As media evaluation
As media evaluationAs media evaluation
As media evaluation
stefan-k
 
Alert centraladminguide
Alert centraladminguideAlert centraladminguide
Alert centraladminguide
Arturo Salgado
 
Doe microgrid workshop aug 30 31 2011 presentations
Doe microgrid workshop aug 30 31 2011 presentationsDoe microgrid workshop aug 30 31 2011 presentations
Doe microgrid workshop aug 30 31 2011 presentations
UCSD-Strategic-Energy
 
Regional Annual Report South Asia 2011
Regional Annual Report South Asia 2011 Regional Annual Report South Asia 2011
Regional Annual Report South Asia 2011
TerredesHommesNL
 
ORNL econ analysis of repurposed EV batteries for Stationary Applications
ORNL econ analysis of repurposed EV batteries for Stationary ApplicationsORNL econ analysis of repurposed EV batteries for Stationary Applications
ORNL econ analysis of repurposed EV batteries for Stationary Applications
UCSD-Strategic-Energy
 

Viewers also liked (20)

Recent Developments in Donard
Recent Developments in DonardRecent Developments in Donard
Recent Developments in Donard
 
[INSIGHT OUT 2011] A23 database io performance measuring planning(alex)
[INSIGHT OUT 2011] A23 database io performance measuring planning(alex)[INSIGHT OUT 2011] A23 database io performance measuring planning(alex)
[INSIGHT OUT 2011] A23 database io performance measuring planning(alex)
 
Java 8 briefing
Java 8 briefingJava 8 briefing
Java 8 briefing
 
Web technologies for desktop development
Web technologies for desktop developmentWeb technologies for desktop development
Web technologies for desktop development
 
Nodejs on 02/22/2012
Nodejs on 02/22/2012Nodejs on 02/22/2012
Nodejs on 02/22/2012
 
As media evaluation
As media evaluationAs media evaluation
As media evaluation
 
Alert centraladminguide
Alert centraladminguideAlert centraladminguide
Alert centraladminguide
 
Catalago
CatalagoCatalago
Catalago
 
US Visas and Violations
US Visas and ViolationsUS Visas and Violations
US Visas and Violations
 
Digital Review. August 2016
Digital Review. August 2016Digital Review. August 2016
Digital Review. August 2016
 
Doe microgrid workshop aug 30 31 2011 presentations
Doe microgrid workshop aug 30 31 2011 presentationsDoe microgrid workshop aug 30 31 2011 presentations
Doe microgrid workshop aug 30 31 2011 presentations
 
Terre des hommes
Terre des hommes Terre des hommes
Terre des hommes
 
July digital review ARTOX media
July digital review ARTOX mediaJuly digital review ARTOX media
July digital review ARTOX media
 
Digital Review, June, 2016
Digital Review, June, 2016Digital Review, June, 2016
Digital Review, June, 2016
 
Regional Annual Report South Asia 2011
Regional Annual Report South Asia 2011 Regional Annual Report South Asia 2011
Regional Annual Report South Asia 2011
 
賽門鐵克 Storage Foundation 6.0 簡報
賽門鐵克 Storage Foundation 6.0 簡報賽門鐵克 Storage Foundation 6.0 簡報
賽門鐵克 Storage Foundation 6.0 簡報
 
Maya global pd 1
Maya global pd 1Maya global pd 1
Maya global pd 1
 
ORNL econ analysis of repurposed EV batteries for Stationary Applications
ORNL econ analysis of repurposed EV batteries for Stationary ApplicationsORNL econ analysis of repurposed EV batteries for Stationary Applications
ORNL econ analysis of repurposed EV batteries for Stationary Applications
 
Madrid protocol
Madrid protocolMadrid protocol
Madrid protocol
 
Node.js ― Hello, world! の1歩先へ。
Node.js ― Hello, world! の1歩先へ。Node.js ― Hello, world! の1歩先へ。
Node.js ― Hello, world! の1歩先へ。
 

Similar to Nodejs first class

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
Shawn Meng
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
Eldar Djafarov
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Alex Su
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
Cosmin Mereuta
 

Similar to Nodejs first class (20)

Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
 
Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017
 
Full Stack Development with Node.js and NoSQL
Full Stack Development with Node.js and NoSQLFull Stack Development with Node.js and NoSQL
Full Stack Development with Node.js and NoSQL
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
5.node js
5.node js5.node js
5.node js
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
Server Side Apocalypse, JS
Server Side Apocalypse, JSServer Side Apocalypse, JS
Server Side Apocalypse, JS
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
NodeJS
NodeJSNodeJS
NodeJS
 

Recently uploaded

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

Nodejs first class

  • 2. Node.js 是什麼 • Javascript 運⾏行平台 • 讓Javascript跳脫瀏覽器的限制 • 輕易建⽴立Web Server • 事件驅動 (Event driven) • ⾮非阻塞式 (Nonblocking)
  • 3. Why Node.js? • 前後端語⾔言統⼀一,且能共⽤用模組 • 其特性⾮非常適合即時網路服務 • 本⾝身就可以是⼀一個HTTP伺服器 • 強⼤大的套件管理及開源社群
  • 4. Why not Node.js? • ⾮非常新的技術,版本甚⾄至還沒1.0 • 對需要⼤大量CPU的⼯工作不拿⼿手 - 直譯式 語⾔言 • library不如其他語⾔言來的多樣及完整 (但在快速發展中)
  • 5. Node.js Dev Env Setup • Install NVM • Using NVM
  • 6. Install NVM • Install NVM https://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
  • 7. Using NVM #列出可安裝的node.js版本 nvm  ls-­‐remote #安裝某版本的nvm nvm  install  0.11 #列出本機端安裝的版本 nvm  ls #使⽤用某版本 nvm  use  0.8 #設定預設版本 nvm  alias  default  0.8
  • 8. Hello World! • helloworld.js • Run: $  node  helloworld.js Hello  World! console.log(“Hello  World!”);
  • 9. Directory Structure project  root/    config/    controllers/    doc/    models/    public/        js/        css/        img/    test/    views/    package.json    README.md
  • 10. 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  Worldn'); }).listen(8124,  "127.0.0.1"); console.log('Server  running  at  http://127.0.0.1:8124/'); $  node  helloserver.js Server  running  at  http://127.0.0.1:8124/
  • 11. Build a HTTP Server - Using Express $  npm  install  express express@3.2.3  node_modules/express ├──  methods@0.0.1 ├──  fresh@0.1.0 ├──  range-­‐parser@0.0.4 ├──  cookie-­‐signature@1.0.1 ├──  qs@0.6.4 ├──  buffer-­‐crc32@0.2.1 ├──  cookie@0.0.5 ├──  debug@0.7.2 ├──  commander@0.6.1 ├──  mkdirp@0.3.4 ├──  send@0.1.0  (mime@1.2.6) └──  connect@2.7.9  (pause@0.0.1,  bytes@0.2.0,  formidable@1.0.13)
  • 12. 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);
  • 13. 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
  • 14. //  Routes app.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);
  • 15. HTML Template - Jade • 網⾴頁的呈現 • 語法簡潔 • http://jade-lang.com/ $  npm  install  jade
  • 16. Jade Template doctype  5 html(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
  • 17. • 套件越⽤用越多,要如何管理? >>> NPM! • package.json Package Management {    "name":  "MessageBoard",    "version":  "0.0.1",    "dependencies":  {        "express":  "*",        "jade":  "*"    } } #幫你安裝package.json裡⾯面所有的套件 $  npm  install
  • 18. Improvement function  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"});        }; });
  • 20. 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
  • 21. About US • http://www.zencher.com/ • 課程:雲端服務開發 http://www.zencher.com/#course/course- cloudapp • https://www.facebook.com/ thingsaboutwebdev