使用node.js搭建伺服器,node.js搭建伺服器
使用node搭建小型伺服器(其實就是分析url然後輸出檔案給用戶端)
最近需要完成一個課程設計,被專案經理(組長)分配寫介面,但是總覺得唯寫前端的話缺了點什麼,所以想自己寫下後端玩一下。
期間還稍微糾結了一下用什麼語言,本來打算正好學習一下PHP,可後來轉念一想,用nodejs豈不美哉,不僅瞭解了後台開發,也相當於鞏固了js基礎,一舉兩得,美滋滋。
在學習node的過程中,學到了使用node實現一個伺服器這一塊,感覺是對前面所學模組的一個很好的總結。用到了四個基本的模組fs stream http path
代碼如下:(內含蹩腳英文注釋請見諒)
'use strict'var url = require('url');var path = require('path');var fs = require('fs');var http = require('http');//get the current path//var root = path.resolve('.');//以當前的目錄為伺服器的根目錄var root = path.resolve(process.argv[2] || '.');//以輸入的參數作為伺服器的根目錄,如果沒有輸入參數就將目前的目錄作為伺服器根目錄console.log('local root dir :' + root);//create servervar server = http.createServer(function(request, response) { //get the path of URL var pathname = url.parse(request.url).pathname; //get the local path var filepath = path.join(root, pathname); //get the file stat and output the request file by callback function fs.stat(filepath, function(err, stat) { if(!err && stat.isFile()) { console.log('200' + request.url); response.writeHead(200); fs.createReadStream(filepath).pipe(response);//沒有必要手動讀取檔案內容。由於response對象本身是一個Writable Stream,直接用pipe()方法就實現了自動讀取檔案內容並輸出到HTTP響應。 } else { console.log('404' + request.url); response.writeHead(404); response.end('404 Not Found'); } });});server.listen(8080);console.log('Server is running at http://127.0.0.1:8080/');
對於其中一些函數的解釋:
path.resolve() 路徑尋航(這名字不錯)path.resolve([from…], to)
有個解釋很有趣:相當於不斷地調用系統的cd指令
eg:
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')//相當於:cd foo/barcd /tmp/file/cd ..cd a/../subfile1path.join([path1],path[2]...) 路徑合并
將所有名稱用path.seq串聯起來,然後用normailze格式化
eg:
path.join('///foo', 'bar', '//baz/asdf', 'quux', '..');=>'/foo/bar/baz/asdf'
既然提到了normalize
那麼:
格式化路徑 path.normalize(p)
將不符合規範的路徑格式化,簡化開發人員中處理各種複雜的路徑判斷
eg:
path.normalize('/foo/bar//baz/asdf/quux/..');=> '/foo/bar/baz/asdf'
http.response.end()結束相應,告訴用戶端所有訊息已經發送。當所有要返回的內容發送完畢時,該函數必須要被調用一次。如果不調用該函數,那麼用戶端將會永遠處於等待狀態。
使用方法:
response.end([data], [encoding])
data end()執行完畢後要輸出的字元,如果指定了 data 的值,那就意味著在執行完 response.end() 之後,會接著執行一條 response.write(data , encoding);
encoding 對應data的字元編碼
以上所述是小編給大家介紹的使用node.js搭建伺服器的方法,希望對大家有所協助,如果大家有任何疑問歡迎給我留言,小編會及時回複大家的,在此也非常感謝大家對幫客之家網站的支援!