NodeJS入门(一)- 基本文件路由实现

    xiaoxiao2021-03-25  104

    使用http和fs模块实现文件路由和基本页面访问【不涉及后台交互】

    分为三个文件: app.js 应用文件(放在项目根目录) server.js 服务器启动文件(放在server目录) route.js 路由文件(放在route目录)

    运行node app.js,即可

    app.js

    var server = require('./server/server'); var router = require('./route/route'); router.setRootPath(__dirname); router.get('/', function(req, res){ router.sendFile(res, "/view/index.html"); });//处理/的get请求 server.start(router);

    server.js

    var http = require('http'); function start(router) { http.createServer(function(request, response) { router.init(request, response); }).listen(8080); console.log('Server 127.0.0.1:8080 starting'); } exports.start = start;

    route.js

    var url = require('url'); var path = require('path'); var querystring = require('querystring'); var fs = require('fs'); module.exports = { fileType: { "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" }, routePathGet: {}, routePathPost: {}, get: function(pathname, fn) { this.routePathGet[pathname] = fn; }, post: function(pathname, fn) { this.routePathPost[pathname] = fn; }, rootPath: "", setRootPath: function(rp) { this.rootPath = rp; }, sendFile: function(response, pathname) { var ext = path.extname(pathname).slice(1); var ft = this.fileType[ext] || "text/plain"; response.setHeader("Content-type", [ft, "charset=utf-8"]); pathname = this.rootPath + pathname; pathname = path.normalize(pathname); fs.readFile(pathname, function(err, data) { if (err) { response.statusCode = 404; response.end('404文件不存在'); } else { response.statusCode = 200; response.end(data, "binary"); } }); }, init: function(request, response) { console.log(request.url); var fn = undefined; var pathname = request.url; if (request.method.toLowerCase() === 'get') { fn = this.routePathGet[pathname]; } else { fn = this.routePathPost[pathname]; } if (fn) { fn(request, response); } else { this.sendFile(response, pathname); } } };

    这里模块编写遵循JS函数式编程规范

    转载请注明原文地址: https://ju.6miu.com/read-19825.html

    最新回复(0)