搭建本地nodeJs服務器

這裏關於nodeJs環境的搭建就不再贅述了。

目錄結構

這裏是我的項目中大概的目錄結構,其實說明的主要是一個相對路徑的關係,具體放在什麼地方都可以

——bin
          |__mine.js
          |__server.js
——build
          |__index.html

廢話不多說,直接上代碼,一些重要的店在註釋中寫了:

代碼

server.js:

var PORT = 3000;//這裏設置的是端口號,訪問url:localhost:3000

var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types; //同級目錄下的mine.js文件,需要node支持的文件類型。
var path=require('path');

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    //這裏是配置項目文件路徑,比如說我的項目是在build目錄下面,build和bin是同級別關系,所以../build進入文件,這樣配置之後在瀏覽器中訪問的url則是:localhost:3000/index.html,有其他文件或者文件夾相應加上目錄即可。
    var realPath = path.join("../build", 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"
};

使用

使用命令行切換到bin目錄下

cd bin/
node server.js

隨即會顯示Server runing at port: 3000.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章