nodejs 實現的簡單server.js模塊 方便本地vue開發調試

ctee8715 7年前發布 | 11K 次閱讀 Vue.js Node.js Node.js 開發

因為最近在學習vue.js,需要渲染網頁。但是搭建php的環境又感覺略復雜,所以用nodejs學習謝了一個server.js 用于方便自己本地的頁面調試。要求的功能如下

  1. 支持html頁面的訪問

  2. 支持默認index.html、index.htm文件訪問

  3. 支持路由+完整路徑訪問

關于第2條,訪問 http://localhost.com:8080/vue/ 指向 vue/index.html文件

項目地址

https://github.com/sunshinev/sunhuajie_node_server

目錄結構

sunhuajie:node sun.huajie$ tree
.
├── index.js // 啟動服務的文件
├── lyric.txt // 讀寫測試的文本文件
├── node_modules
│   └── huajie_server // 自定義模塊
│       ├── package.json // 模塊配置
│       ├── requesthandler.js // 請求處理腳本
│       ├── router.js // 路由腳本
│       └── server.js // 服務創建腳本
└── vue // 工作目錄
    └── index.html

服務創建過程

index.js 啟動

因為將server封裝為了一個模塊,所以每次啟動的時候只需要引入,然后node index.js就可以了。

#!/usr/bin/env node

var server = require('huajie_server');
server.create();

效果如圖:

sunhuajie:node sun.huajie$ node index.js
the port is 8080

server.js 創建服務

_onRequest 實現了對請求的處理,并且作為閉包傳遞給 http.createServer 。狀態碼由路由層進行返回。

#!/usr/bin/env node

var http = require('http');
var router = require('./router');

// 創建server 默認端口為8080
function create(port = 8080) {
    console.info('the port is '+port);
    http.createServer(_onRequest).listen(port);
}

// 處理請求
function _onRequest(request, response) {
    // 路由
    var res = router.route(request.url);
    // 狀態碼
    response.writeHead(res.code,{});
    // 響應內容
    response.write(res.content);
    response.end();
}

exports.create = create;

router.js 路由

路由此處跟php的mvc的 dispatcher (分發器)很像,分析url參數以及目錄,實現文件指向。 這里有個小問題,就是當時寫這個router的時候,其實應該將 requesthandler.js 里面的關于文件判斷的部分放到router里面才算合理。但是當時為了方便就直接寫到requesthandler里面了(后面給大家看這個文件)。

在路由這一層,實際上還可以添加一個 rewrite 的配置。先分析 url ,通過 rewrite 重新指向后,再把指向后的地址傳遞給 requesthandler 進行處理。

#!/usr/bin/env node

var url = require('url');
var querystring = require('querystring');
var requesthandler = require('./requesthandler');

// todo 后期可以擴展路由部分

function route(request_url) {
    // 解析地址
    var url_parse = url.parse(request_url);
    var url_path = url_parse['path'];

    var res = {};
    var code = 200;
    // 判斷路徑是否存在
    var content = requesthandler.handle(url_path);

    return {
        'code':code,
        'content':content
    }
}

exports.route = route;

requesthandler.js 請求處理+文件指向

這個文件最簡單的目的是實現對html文件的讀取以及輸出。但是我們加了一層默認文件,所以需要對目錄進行遍歷,并且判斷當前的childnode是dir還是file。

默認可以訪問 index.html 和 index.htm 兩個文件。

_findFile 方法,首先判斷當前傳遞的file_path是否是存在的文件,如果不是文件,那么在這個目錄層級中進行搜索,是否存在默認可以訪問的文件。進行遍歷的時候,沒有使用 forEach ,因為會遍歷所有的文件,無論中間是否有 return 。

_isFile 方法,使用了try catch ,因為 fs.statSync 在文件不存在的時候,會拋出錯誤,導致腳本終止。

#!/usr/bin/env node

var fs = require('fs');

// 默認檢索文件,可以修改為配置項
var default_files = [
    'index.htm',
    'index.html'
];

function handle(url_path) {
    // 文件路徑構造
    var file_path = '.' + url_path;
    // 判斷路徑是否存在
    var f_path = _findFile(file_path);

    if(!f_path) {
        return 'the path "'+file_path+'" is not exist';
    }else {
        var content = fs.readFileSync(f_path);
        return content;
    }
}
/**
 * 檢索目錄下的不同文件名是否存在,建立優先級
 * @return {[type]} [description]
 */
function _findFile(file_path) {
    var is_file = _isFile(file_path);
    // 如果文件存在,直接返回路徑
    if(is_file) {
        return file_path;
    }
    // 文件不存在,構造路徑尋找文件
    var regex = /^\.\/[\w]*([\/][\w]+)?/;
    var regex_res = file_path.match(regex);
    // 匹配出目錄路徑 ./vue/test/s => ./vue/test
    if(!regex_res) {
        return '';
    }else {
        // 這里沒有使用forEach,因為會遍歷所有的值
        for(var i=0; i<default_files.length; i++) {
            var new_path = regex_res[0]+'/'+default_files[i];
            if(_isFile(new_path)) {
                return new_path;
            }
        }
    }
}
/**
 * 文件是否存在
 * @param  {[type]}  file_path [description]
 * @return {Boolean}           [description]
 */
function _isFile(file_path) {
    try {
        // 同步會拋出異常,所以用try來保證正常執行
        var stat = fs.statSync(file_path);
        // 返回是否是文件
        return stat.isFile();
    }catch(e) {
        console.info(e.message);
    }


}

exports.handle = handle;

最終效果

啟動

sunhuajie:node sun.huajie$ node index.js
the port is 8080

瀏覽器訪問

訪問 實際
http://localhost:8080/vue/ 指向 index.html
http://localhost:8080/vue 指向 index.html
http://localhost:8080/ the path "./" is not exist
http://localhost:8080/vue/s the path "./vue/s" is not exist

 

來自:https://segmentfault.com/a/1190000008307856

 

 本文由用戶 ctee8715 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!