SlideShare a Scribd company logo
Node.js從無到有
MiCloud Team
Simon
https://sites.google.com/a/mitac.com.tw/training/
Prepare
Node.js: http://nodejs.org
Github: https://githib.com
IDE
● vi / vim
● Sublime text: http://www.sublimetext.com/
● Eclipse based IDE:
○ Apatana: http://www.aptana.com/
○ Titanium: http://www.appcelerator.com/platform/titanium-
studio/
● Cloud IDE:
○ cloud9: https://c9.io
Objective
● 簡介Node.js
● 從安裝開始
● 第一個Node.js程式
● 基礎介紹
● NPM(Node.js Package Management)
● Node.js的MVC - Express + EJS
Node.js簡介
一鍵安裝
http://nodejs.org/download/
進階安裝
● Download source code
● Install
tar -zxf node-vx.x.x.tar.gz
cd node-vx.x.x
./configure --prefix=/opt/node
make
sudo make install
● Github:
● Installation:
curl https://raw.github.com/creationix/nvm/master/install.sh | sh
nvm install 0.10
● Switch Node.js version:
nvm use 0.10
NVM安裝
參考:http://opennodes.arecord.us/md/BasicNodeJS.md
檢視是否安裝成功
● node -v
● npm -v
● which node (for linux)
# node
> console.log(‘Hello Word’);
Hello Word
>
Node.js直譯模式
第一個Node.js程式
var http = require('http');
/**
* 透過http模組啟動web server服務
*/
http.createServer(function (req, res) {
//設定回應為text文件,並回應Hello World
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
}).listen(1337, '127.0.0.1'); //設定服務聽取127.0.0.1位置的1337 port
Lab 1 - Hello World app
● 建立一個Hello World網站
基礎介紹
● 基礎語法介紹
● 基本模組介紹
● JSON
基礎語法
● 語法使用上同JavaScript
● 差別 - Node.js是Server Side程式語言
● Assertion Testing
● Buffer
● C/C++ Addons
● Child Processes
● Cluster
● Console
● Crypto
● Debugger
● DNS
● Domain
● Events
● File System
● Globals
● HTTP
● HTTPS
● Modules
● Net
● OS
● Path
● Process
● Punycode
● Query Strings
● Readline
● REPL
● Stream
● String Decoder
● Timers
● TLS/SSL
● TTY
● UDP/Datagram
● URL
● Utilities
● VM
● ZLIB
模組的使用
載入模組
● var fs = require(‘fs’);
● var mylib = require(‘./mylib’);
發佈模組
● exports.fn = function(...){...}
Node.js與環境變數
/* From: http://opennodes.arecord.us/md/NodeJSEnv.md */
var param = '';
/**
* 關於指令列的接入參數,可以透過process.argv這個變數來讀取
* 而process.argv[0] = node這個指令,
* process.argv[1] = 要執行的node.js程式檔名
* 從argv[2]之後的才開始是讀入的參數
*/
if ( process.argv[2] ) param = process.argv[2];
if(param != '')
console.log(param);
else
console.log('No input param');
fs module
● var fs = require(‘fs’)
● fs.readFile(‘path’, callback)
● fs.readFileSync(‘path’)
var fs = require('fs')
/**
* readdirSync function提供同步的資料夾列表,
* 回傳值為一個file的陣列
*/
var files = fs.readdirSync('.');
for ( i in files ) {
console.log(files[i]);
}
child_process.exec
var exec = require('child_process').exec;
/**
* 透過exec執行”command”,並於callback中接收回傳結果
*/
child = exec("command",
function (error, stdout, stderr) {
…
}
);
socket
var net = require('net');
var client = new net.Socket();
//使用port與host來設定socket物件
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
//接收到data的處理
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
Node.js的物件 - JSON
初始化
● var json = {};
● var json = { "key" : "value" };
賦值
● json.key = 'value';
● json['key'] = 'value';
● json.fn = function(...) {...}
取值
● json.key
● json[‘key’]
刪除屬性
● delete json.key
JSON的操作
Lab 2 - Lightware HTTP Server
● 透過fs模組讀取某個目錄底下的文件,並提供
給http模組做呈現
NPM
● 基本操作
● 好用的模組工具
模組的安裝 - NPM
搜尋
● npm search [模組名稱]
安裝
● npm install [模組全名] [-g] [--save]
● npm install [模組全名]@[版本]
詳細檢視
● npm show [模組全名]
刪除
● npm remove [模組全名] [-g]
mysql module
基本資訊
● https://github.com/felixge/node-mysql
安裝
● npm install mysql
操作
● var mysql = new require('mysql'),
● db = mysql.createConnection({....});
● db.query(sql, condition, function(err, rows, fields){...})
forever module
基本資訊
● http://github.com/nodejitsu/forever.git
安裝
● npm install forever -g
操作
● forever start [path to executable js]
● forever stop [path to executable js]
● forever restart [path to executable js]
● forever list
underscore.js
基本資訊
● Github: https://github.com/documentcloud/underscore.git
● 官網:http://underscorejs.org/
安裝
● npm install underscore
操作
● var _ = require(‘underscore’)
● _.isEmpty(obj);
● _.pick(arr, [‘field1’, ‘field2’]);
● _.keys(obj)
express
基本資訊
● https://github.com/visionmedia/express
● http://expressjs.com
安裝
● npm install express -g
操作
● express -e -s [project name]
● cd [project name] && npm install
Node.js MVC - ExpressJS
● Express基本結構
● EJS
● EJS-Partial
Express基本結構
專案定義檔,包含模組相依
程式啟動點,包含route設定
預設靜態資源位置,可存放 html, js,
image, css...
route相關設定,存放從app.js模組化出來
的routes
views相關設定,存放ejs檔案,為view層顯
示相關的檔案
基本資訊
● Github: https://github.com/visionmedia/ejs
優點:
● 採用html語法作為基礎
● 結合express-partials可以提供樣板功能
操作:
● app.js
● views/index.ejs
● routes/index.js
EJS模組
EJS - app.js, index.js
# app.js
….(skip)
app.set('view engine', 'ejs');
….(skip)
# routes/index.js
exports.index = function(req, res){
//透過res.render設定導向的頁面與參數集合
res.render('index', { title: 'Express' });
};
….(skip)
指定本專案使用ejs作為view engine
routes中使用res.render()來指定要輸出的
頁面位置(在此為index),以及要帶過去的
參數集合(在此為{ title: 'Express' })
EJS - index.ejs
# views/index.ejs
<%= title %>
Welcome to <%= title %>
使用<%=...%>將後方title參數值做呈現
<% if(title == ‘express’){ %>
Default title: <%- title %>
<% } %>
使用<%...%>內嵌Node.js運算語法
使用<%-...%>將title值帶入
(與<%=..%>不同的是,此處帶入的 值將不
會做html標籤跳脫)
EJS - express-partials模組
● Github: https://github.com/publicclass/express-partials
● 安裝:npm install express-partial --save
# app.js
var express = require('express')
, partials = require('express-partials')
, app = express();
app.use(partials());
# views/index.ejs
app.get('/test', function(req, res) {
...
res.render('page_name',
{layout: 'your_layout', obj: 'your objects...'});
});
Lab 3 - Express + MySQL的應用
● 建立Express+Ejs網站,使用jetstrap樣板
● 連線MySQL實作用戶資料的新、刪、改、查
自建npm模組
● 基本設定
● 發佈
自建NPM模組
● Got your npm account: https://npmjs.
org/signup
● Prepare:
○ package.json
○ module dependency and you implements
$ mkdir node_modules/mymodule
$ cd node_modules/mymodule
$ vi package.json
$ vi index.js
$ npm publish
發佈NPM模組
{ "name": "application-name",
"version": "0.0.1",
"main":"index",
"dependencies": {
"nodeutil": "0.0.27" }}
var exports = module.exports;
exports.test = function(){
….
}
var mymodule = require(‘mymodule’);
mymodule.test();
use
Lab 4 - 建立自己的Hello World模組
● 申請NPM帳戶
● 寫個Hello World模組
● 發佈到NPM
更多Node.js模組介紹
http://opennodes.arecord.us
按
個
讚
吧
~
END - Q&A

More Related Content

PDF
NodeJS基礎教學&簡介
PDF
Alphorm.com Formation Vue JS 3 : Exploiter la Composition API
PDF
Androidの新ビルドシステム
PDF
カスタムROM開発者の視点から見たAndroid
PPTX
NodeJS - Server Side JS
PPT
フィルタドライバ入門
PPTX
Android bootup process
PPTX
Net core
NodeJS基礎教學&簡介
Alphorm.com Formation Vue JS 3 : Exploiter la Composition API
Androidの新ビルドシステム
カスタムROM開発者の視点から見たAndroid
NodeJS - Server Side JS
フィルタドライバ入門
Android bootup process
Net core

What's hot (20)

PDF
Aosp+
PDF
Android Boot Time Optimization
PDF
Androidのリカバリシステム (Androidのシステムアップデート)
PDF
Node JS Crash Course
PDF
AndroidとSELinux
PDF
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
PDF
微服務對IT人員的衝擊
ODT
Comprendre les scripts shell auto-extractible
PPTX
An Intro into webpack
PPTX
Android組込み開発基礎コース Armadillo-440編
PDF
Support NodeJS avec TypeScript Express MongoDB
PPTX
Webpack Introduction
PDF
Présentation de Django @ Orange Labs (FR)
PDF
これからはじめる XAML - WPF プログラミング
PPTX
Gnu debugger
PDF
Linux Locking Mechanisms
PDF
Launch the First Process in Linux System
PDF
Introduction à React
PDF
Qt Installer Framework
 
Aosp+
Android Boot Time Optimization
Androidのリカバリシステム (Androidのシステムアップデート)
Node JS Crash Course
AndroidとSELinux
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
微服務對IT人員的衝擊
Comprendre les scripts shell auto-extractible
An Intro into webpack
Android組込み開発基礎コース Armadillo-440編
Support NodeJS avec TypeScript Express MongoDB
Webpack Introduction
Présentation de Django @ Orange Labs (FR)
これからはじめる XAML - WPF プログラミング
Gnu debugger
Linux Locking Mechanisms
Launch the First Process in Linux System
Introduction à React
Qt Installer Framework
 
Ad

Similar to Node.js從無到有 基本課程 (20)

PDF
北護樂學程式冬令營 2017
PPTX
快速入坑 Node.js - 0613 SITCON 雲林定期聚
PPTX
深入淺出Node.JS
PDF
Node.js 入門 - 前端工程開發實務訓練
PDF
Noder eyes for frontend guys
PPTX
前端自動化工具
PPTX
180518 ntut js and node
PDF
Node.js 進攻桌面開發
PPTX
猴子也能懂的Node.js
PDF
以Code igniter為基礎的網頁前端程式設計
PDF
Node.js with express
PPTX
Nodejs introduce - using Socket.io
PPTX
NODEjs Lesson1
PDF
COSCUP 2010 - node.JS 於互動式網站之應用
PDF
如何在有限資源下實現十年的後端服務演進
PDF
KSDG meet-up #1
PDF
前端爆肝之旅+React上山前的小專案心得分享
PDF
程式人雜誌 -- 2015 年1月號
PPT
Bluemix Node-Red Part II
PPTX
Nodejs api server_implement
北護樂學程式冬令營 2017
快速入坑 Node.js - 0613 SITCON 雲林定期聚
深入淺出Node.JS
Node.js 入門 - 前端工程開發實務訓練
Noder eyes for frontend guys
前端自動化工具
180518 ntut js and node
Node.js 進攻桌面開發
猴子也能懂的Node.js
以Code igniter為基礎的網頁前端程式設計
Node.js with express
Nodejs introduce - using Socket.io
NODEjs Lesson1
COSCUP 2010 - node.JS 於互動式網站之應用
如何在有限資源下實現十年的後端服務演進
KSDG meet-up #1
前端爆肝之旅+React上山前的小專案心得分享
程式人雜誌 -- 2015 年1月號
Bluemix Node-Red Part II
Nodejs api server_implement
Ad

More from Simon Su (20)

PDF
Kubernetes Basic Operation
PDF
Google IoT Core 初體驗
PDF
JSDC 2017 - 使用google cloud 從雲到端,動手刻個IoT
PDF
GCPUG.TW meetup #28 - GKE上運作您的k8s服務
PDF
Google Cloud Platform Special Training
PDF
GCE Windows Serial Console Usage Guide
PDF
GCPNext17' Extend 開始GCP了嗎?
PDF
Try Cloud Spanner
PDF
Google Cloud Monitoring
PDF
Google Cloud Computing compares GCE, GAE and GKE
PDF
JCConf 2016 - Google Dataflow 小試
PDF
JCConf 2016 - Dataflow Workshop Labs
PDF
JCConf2016 - Dataflow Workshop Setup
PDF
GCPUG meetup 201610 - Dataflow Introduction
PDF
Brocade - Stingray Application Firewall
PDF
使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析
PDF
Docker in Action
PDF
Google I/O 2016 Recap - Google Cloud Platform News Update
PDF
IThome DevOps Summit - IoT、docker與DevOps
PDF
Google Cloud Platform Introduction - 2016Q3
Kubernetes Basic Operation
Google IoT Core 初體驗
JSDC 2017 - 使用google cloud 從雲到端,動手刻個IoT
GCPUG.TW meetup #28 - GKE上運作您的k8s服務
Google Cloud Platform Special Training
GCE Windows Serial Console Usage Guide
GCPNext17' Extend 開始GCP了嗎?
Try Cloud Spanner
Google Cloud Monitoring
Google Cloud Computing compares GCE, GAE and GKE
JCConf 2016 - Google Dataflow 小試
JCConf 2016 - Dataflow Workshop Labs
JCConf2016 - Dataflow Workshop Setup
GCPUG meetup 201610 - Dataflow Introduction
Brocade - Stingray Application Firewall
使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析
Docker in Action
Google I/O 2016 Recap - Google Cloud Platform News Update
IThome DevOps Summit - IoT、docker與DevOps
Google Cloud Platform Introduction - 2016Q3

Node.js從無到有 基本課程