Nodejs學(xué)習(xí)筆記-路由改造

代碼:https://github.com/fengchunjian/nodejs_examples/tree/master/routerv5

//vim views/login.html
<html>
<head>
</head>
<body>
登錄界面
![](./readImg)
</body>
</html>
//vim models/optfile.js
var fs = require('fs')
module.exports = {
    readImg : function(path, res) {
        fs.readFile(path, "binary", function(err, file) {
            if (err) {
                console.log(err);
                return;
            } else {
                console.log("異步讀取圖片完成");
                res.write(file, "binary");
                res.end();
            }
        });
    },
    writefile : function(path, data, recall) {
        fs.writeFile(path, data, function(err) {
            if (err) {
                throw err;
            }
            console.log("異步寫文件完成");
            recall("異步寫文件完成");
        });
    },
    readfile : function(path, recall) {
        fs.readFile(path, function(err, data) {
            if (err) {
                console.log(err);
            } else {
                recall(data);
            }
        });
        console.log("異步讀文件完成");
    },
}
//vim models/router.js
var optfile = require("./optfile");
function getRecall(req, res) {
    res.writeHead(200, {'Content-Type':'text/html;charset=utf-8'});
    function recall(data) {
        res.write(data);
        res.end();
    }
    return recall;
}
module.exports = {
    readImg : function(path, res) {
        res.writeHead(200, {'Content-Type':'image/jpeg'});
        optfile.readImg("./imgs/nodejs.jpg", res);
    },
    writefile : function(req, res) {
        recall = getRecall(req, res);
        optfile.writefile("./file.txt", "異步文件寫入", recall);
    },
    login : function(req, res) {
        recall = getRecall(req, res);
        optfile.readfile("./views/login.html", recall);
    },
    zhuce : function(req, res) {
        recall = getRecall(req, res);
        optfile.readfile("./views/zhuce.html", recall);
    }
}
//vim routercall.js
var http = require('http');
var url = require('url');
var router = require('./models/router');
http.createServer(function (request, response) {
    if(request.url!=="/favicon.ico") {
        var pathname = url.parse(request.url).pathname;
        pathname = pathname.replace(/\//, '');
        router[pathname](request, response);
        console.log("主程序執(zhí)行完畢");
    }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

node routercall.js
Server running at http://127.0.0.1:8000/
異步讀文件完成
主程序執(zhí)行完畢
主程序執(zhí)行完畢
異步讀取圖片完成

http://localhost:8000/login

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容