over 9 years ago

這學期碰了不少網頁開發的技術,還想學更多,先從Node.js下手

前言

之前一直是處於:需要寫什麼功能,就去網路爬code看懂自己修改,
其實對於這些網頁相關的程式語言一直都沒有弄懂,就花了些時間了解各個程式語言的功用

Step1. 安裝

我的環境是Windows7 64bit,先去此地下載Windows 64bit的.msi檔來安裝
就用default值,一直下一步,然後就安裝完成啦

Step2. 撰寫第一個程式 Hello World

新增一個01-console_hello_world.js的檔案,不免俗當然就寫個第一個"你好世界"的程式

console.log("Hello World");

Step3. 執行

開啟command line 輸入node 01-console_hello_world.js
這時終端就會輸出 Hello World

小筆記個(在Windows常會習慣打Unix指令阿@@)
Windows Unix
cd /d cd
dir ls

不過如果只是寫個普通會Output 的程式也太無聊了吧
來寫個比較實用跟Web相關的程式:基礎 HTTP 伺服器
建立一個 02-basic_http_hello_world.js 的檔案

var ip   = "127.0.0.1",
    port = 1337,
    http = require('http');

function onRequest(request, response) {
  console.log("Request received.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}
http.createServer(onRequest).listen(port, ip);
console.log("Server has started.");

我們載入http模組,利用內建的createServer架設一個基本的HTTP伺服器
用一個call back function接收HTTP伺服器的 request& response
最後HTTP伺服器需要設定listen的port還有IP,監聽所有HTTP伺服器行為
並同時將server收到的訊息顯示在終端上(console.log)
// http.createServer(onRequest) 這裡是Javascript中常見的函數傳遞

在command line執行node 02-basic_http_hello_world.js
終端機上面會顯示"Server has started"

這時候在瀏覽器上打localhost:1337就可以看到是"Hello World"的頁面
此時終端機會顯示1~2的"Request received." (觸發onRequest callback)
這是因為大部分的瀏覽器會在存取 http://localhost:1337 的時候,
還會嘗試讀取 http://localhost:1337/favicon.ico

這裡的運作方式是,onRequest函數被觸發之後,有兩個參數request, response被傳入
我們不在乎request的內容,所以就放著不處理
而利用response回傳一個200 HTTP 狀態碼(200代表OK),
write函數在content-type:text/plain的HTTP的header寫上"Hello World",再用end函數結束完成回應。
response的write、end函數,都被定義在Class: http.ServerResponse中。

References

Node入門
Node.js 基礎 Node.js 中文電子書

← Git 筆記 - 其他 Git Server Node.js 練習 - HTTP 路徑(route)建立 →
 
comments powered by Disqus