nodejs搭建本地http服務器


由於不做php相關的東西,懶得裝apache,干脆利用nodejs搭建一個本地的服務器用於測試。

nodejs這玩意兒吧,對做前端的介入后端簡直就是一把利器。而且目前,nodejs也越來越有商用價值。

nodejs其實是非常底層的,從功能上說,它既是apache也是php。像搭建http服務器這種功能,本來是apache已經封裝好的,但nodejs需要我們手動來搭建。其實在實際應用中,我們可以使用現成的框架。但這里,我想手動搭建,也加深一下對http服務器的理解。

我們node執行下面這個文件,我命名為http.js,它將創建一個httpServer並監聽3000端口。

var PORT = 3000;

var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;
var path=require('path');

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join("assets", pathname);
    //console.log(realPath);
    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';
    fs.exists(realPath, function (exists) {
        if (!exists) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });

            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    response.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
                    response.end(err);
                } else {
                    var contentType = mine[ext] || "text/plain";
                    response.writeHead(200, {
                        'Content-Type': contentType
                    });
                    response.write(file, "binary");
                    response.end();
                }
            });
        }
    });
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

上面我們還引入了一個mine.js,這是我自己寫的,里面存儲的是名值對,用於定義不同后綴的文件所對應的返回方式:

exports.types = {
  "css": "text/css",
  "gif": "image/gif",
  "html": "text/html",
  "ico": "image/x-icon",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "js": "text/javascript",
  "json": "application/json",
  "pdf": "application/pdf",
  "png": "image/png",
  "svg": "image/svg+xml",
  "swf": "application/x-shockwave-flash",
  "tiff": "image/tiff",
  "txt": "text/plain",
  "wav": "audio/x-wav",
  "wma": "audio/x-ms-wma",
  "wmv": "video/x-ms-wmv",
  "xml": "text/xml"
};

fs模塊是用於讀取文件的,提供讀取文件的方法,其實仔細研究文檔會發現,它有同步和異步兩種讀取方式。fs.exists這個方法網上很多文章寫作path.exists,,現在推薦寫作fs.exists這個方法。否則會報警:

需要注意的是,不僅瀏覽器訪問html文件會形成一次訪問,里面鏈接的js,css等外部文件也會分別形成一次http訪問。所以,http.createServer的回調其實是在一次頁面訪問中執行了多次的。我們console.log(realPath)一下就可以看到:

 

這里並沒有加入默認訪問index.html的功能,所以訪問地址要寫全http://127.0.0.1:3000/index.html


免責聲明!

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



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