利用 nodeJS 搭建一個簡單的Web服務器(轉)


下面的代碼演示如何利用 nodeJS 搭建一個簡單的Web服務器:

1. 文件 WebServer.js:

//------------------------------------------------ 
// 利用nodejs搭建一個簡單的Web服務器 
//------------------------------------------------ 

//啟動計時器,記錄啟動服務所花費的時間
console.time('start WebServer need time');

//請求模塊 
var libHttp = require('http');  //HTTP協議模塊 
var libUrl = require('url');    //URL解析模塊 
var libFs = require("fs");      //文件系統模塊 
var libPath = require("path");  //路徑解析模塊 

//依據路徑獲取返回內容類型字符串,用於http響應頭 
var funGetContentType = function (filePath) {
    var contentType = "";
    
    //使用路徑解析模塊獲取文件擴展名 
    var ext = libPath.extname(filePath);
    
    switch (ext) {
        case ".html":
            contentType = "text/html";
            break;
        case ".js":
            contentType = "text/javascript";
            break;
        case ".css":
            contentType = "text/css";
            break;
        case ".gif":
            contentType = "image/gif";
            break;
        case ".jpg":
            contentType = "image/jpeg";
            break;
        case ".png":
            contentType = "image/png";
            break;
        case ".ico":
            contentType = "image/icon";
            break;
        default:
            contentType = "application/octet-stream";
    }
    
    //返回內容類型字符串 
    return contentType;
}

//Web服務器主函數,解析請求,返回Web內容 
var funWebSvr = function (req, res) {
    //獲取請求的url 
    var reqUrl = req.url;
    
    //向控制台輸出請求的路徑 
    console.log(reqUrl);
    
    //使用url解析模塊獲取url中的路徑名 
    var pathName = libUrl.parse(reqUrl).pathname;    
    if (libPath.extname(pathName) == "") {
        //如果路徑沒有擴展名 
        pathName += "/"; //指定訪問目錄 
    }
    if (pathName.charAt(pathName.length - 1) == "/") {
        //如果訪問目錄 
        pathName += "index.html"; //指定為默認網頁 
    }
    
    //使用路徑解析模塊,組裝實際文件路徑 
    var filePath = libPath.join("./WebRoot", pathName);
    
    //判斷文件是否存在 
    libFs.exists(filePath, function (exists) {
        //文件存在
        if (exists) {
            //在響應頭中寫入內容類型 
            res.writeHead(200, { "Content-Type": funGetContentType(filePath) });
            
            //創建只讀流用於返回 
            var stream = libFs.createReadStream(filePath, { flags: "r", encoding: null });
            
            //指定如果流讀取錯誤,返回404錯誤 
            stream.on("error", function () {
                res.writeHead(404);
                res.end("<h1>404 Read Error</h1>");
            });
            
            //連接文件流和http返回流的管道,用於返回實際Web內容 
            stream.pipe(res);
        }
        else {
            //文件不存在,返回404錯誤 
            res.writeHead(404, { "Content-Type": "text/html" });
            res.end("<h1>404 Not Found</h1>");
        }
    });
}

//創建一個http服務器 
var webSvr = libHttp.createServer(funWebSvr);

//指定服務器錯誤事件響應 
webSvr.on("error", function (error) {
    //在控制台中輸出錯誤信息 
    console.log(error); 
});

//開始偵聽8124端口 
webSvr.listen(8124, function () {
    //向控制台輸出服務啟動的信息 
    console.log('WebServer running at http://127.0.0.1:8124/');
    
    //關閉服務啟動計時器
    console.timeEnd('start WebServer need time');
});

2.文件 index.html:

<!DOCTYPE html>
<html>
<head>
    <meta />
    <title>Node.js Web Server</title>
</head>
<body>
    <h1>Node.js Web Server</h1><hr>
    <div id="container">
        <a href="http://nodejs.cn/">
            <img src="images/home.jpg" alt="Node" width="480" height="300" />
        </a>
    </div>
</body>
</html>

3.服務器文件目錄:

4.運行結果:

在服務器根目錄下打開 cmd 並運行 node WebServer 命令,然后在瀏覽器中輸入 http://localhost:8124/ 即可查看。

 

 原文地址:http://www.jb51.net/article/29865.htm


免責聲明!

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



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