nodejs - 創建服務器(1)


在此之前,確保你已經安裝了Node(並且你很會折騰) - 有人說,Java腳本和Java最本質的區別就是一個超會更新,一個死守舊。

如果你沒有安裝,請去官網下載並且安裝:http://nodejs.cn/download/

中文文檔:http://nodejs.cn/api/

 

 

先來說說node的優點以及缺點

粗略的來說node的優點即在於它是單線程、運行環境要求低,缺點同樣明顯的就是它一旦出現問題,全部癱瘓。

而php和java是多線程運行的,互不影響,但占資源高。

 

看一個小例子(菜鳥教程里面的)

 1 var http = require('http');  2 
 3 http.createServer(function(request, response) {  4 
 5     // 發送 HTTP 頭部 
 6     // HTTP 狀態值: 200 : OK
 7     // 內容類型: text/plain
 8     response.writeHead(200, { 'Content-Type': 'text/plain' });  9 
10     // 發送響應數據 "Hello World"
11     response.end('Hello World\n'); 12 }).listen(8888); 13 
14 // 終端打印如下信息
15 console.log('Server running at http://127.0.0.1:8888/');

 

 1 // 請求http包
 2 var http = require('http');  3 
 4 // 創建一個http線程
 5 http.createServer(function(request, response) {  6 
 7     // 發送 HTTP 頭部 
 8     // HTTP 狀態值: 200 : OK
 9     // 內容類型: text/plain
10     response.writeHead(200, { 'Content-Type': 'text/plain' }); 11 
12     // 發送響應數據 "Hello World"
13     response.end('Hello World\n'); 14 }).listen(8888); 15 
16 // 終端打印如下信息
17 console.log('Server running at http://127.0.0.1:8888/');

 

很好,可以運行

默認本地:127.0.0.1

端口自設:8088

 

我們看看官網API(http自帶server)

 

且每一段代碼都會帶上res.end() , 這是因為我們要告訴服務器已經完成了.

 

再來看看這一段代碼

 1 var http = require('http');
 2 var fs = require('fs');
 3 
 4 var server = http.createServer(function(req, res) {
 5 
 6     // 請求路由 ==是指字符串比較
 7     if (req.url == "/index") {
 8         fs.readFile('index.html', function(err, data) {
 9             res.writeHead(200, { "Content-type": "text/html;charset=utf-8" });
10             res.end(data);
11         });
12     } else {
13         fs.readFile('404.html', function(err, data) {
14             res.writeHead(200, { "Content-type": "text/html;charset=utf-8" });
15             res.end(data);
16         });
17     }
18 });
19 
20 server.listen(80, '127.0.0.1');

 

 1 // 導入http
 2 var http = require('http');
 3 // 導入fs(文件讀取服務)
 4 var fs = require('fs');
 5 
 6 var server = http.createServer(function(req, res) {
 7     // 其實nodejs最難的一點就是管理路由 - 它和其它web服務器不一樣(因此靈活性超強)
 8 
 9     // 請求路由 ==是指字符串比較
10     if (req.url == "/index") {
11         // 請求地址index,讀取文件index.html
12         fs.readFile('index.html', function(err, data) {
13             res.writeHead(200, { "Content-type": "text/html;charset=utf-8" });
14             res.end(data);
15         });
16     } else {
17         // 請求地址不存在,讀取文件404.html,並且返回
18         fs.readFile('404.html', function(err, data) {
19             // 請求頭 - 根據類型不同而不同
20             res.writeHead(200, { "Content-type": "text/html;charset=utf-8" });
21             res.end(data);
22         });
23     }
24 });
25 
26 // 監聽80端口,並且是本地地址
27 server.listen(80, '127.0.0.1');

 

 

通過 localhost/index 就可以訪問到

index.html了。

 

通過localhost/other 就可以訪問到

其它頁面了。

 

 

你試一試鏈接本地圖片或者css以及其它資源,感受一下node路由的強大!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM