nodejs lesson1
TRANSCRIPT
Lesson 1By BigQ
Content• What is Node.js• Introduction• Write and Run the Node.js
HelloWorld• Build a Website
Build a basic HTTP serverBuild an index
Node.js ?
網站
後台 前台管理與維護網站 讓人看到的網站樣式
PHP, Python, and Ruby… JavaScript
Node.js ?
網站
後台 前台管理與維護網站 讓人看到的網站樣式
PHP, Python, and Ruby… JavaScript
• JavaScript programming environment• Use V8 runtime• Event Driven• Non-blocking libraries • Supports CommonJS module format• Supports C/C++ base add-ons
Introduction
Write and Run the Node試著寫一個程式
讓 Node 可以讀取它的內容
Hello world!1. 用任何一個文字編輯器輸入
console.log('Hello World');並儲存成 helloworld.js
2. 用 Node.js Command prompt 在目錄下鍵入 node helloworld.js
Hello world!
終端顯示出 Hellow World
Build a Website
FirstWe need a HTTP server !!
Build a basic HTTP server
我們對 node 內建的 http 模組提出請求(require)並讓宣告變數 setver 用 listen 這個方法對埠號 3000 進行偵聽
Build a basic HTTP server
加入一個狀態 (200) 以及 HTTP 頭的內容類型(Content-Type) ,使用 response.write() 函數在 HTTP 發送文字 "Hello World" 。最後,我們執行 response.end() 完成回應。
Build a basic HTTP server
1. 透過 Node.js 來執行你的伺服器
2. 在網址列輸入localhost:3000
Build a basic HTTP server
增加一個函數 onRequest ,把所有的回應用函數處理,如果請求執行 onRequest 成功,會顯示 Request received.如果請求執行 http 成功,會顯示 Server has started.
Build a basic HTTP server
目前而言,我們已經建立了一個基本的伺服器,但是沒有給予任何的命令 (request) 。
Build a basic HTTP server
如果想要在伺服器裡面編輯網頁內容的話,整個 server 會變得亂七八糟,無從讀起。
或許可以試著把剛剛的 server.js 設成一個我們自己的模組,只要用 require 請求執行server 的動作,那就可以清楚分工了 !
Build an Index
新定義一個函數 start ,這函數包含了剛剛所有的動作,最後匯出函數 start 。
Build an Index編輯一個檔案與 server.js 同目錄,名為index.js
經過我們對 server 的宣告,執行 index.js 的時候會請求啟動這模組,而這模組就是我們剛剛建立的 server.js ,然後 server 會讀取函數start 。
Build an Index
就這樣輕鬆讓 server 負責他的工作, index可以負責自己的工作了 !
現在我們不用再執行 server.js ,只要執行index.js 就會啟動 server.js 了。