這篇文章給大家介紹使用node.js怎么搭建一個服務器,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
'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 server
var 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/bar
cd /tmp/file/
cd ..
cd a/../subfile1
path.join([path2],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怎么搭建一個服務器就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。