Node.js后端服务器框架 发表于 2018-05-11 | 分类于 Node.js 作用1234本地开启服务器根据路径mock数据读取静态文件支持模板引擎渲染 目录结构 12345678910111213141516171819202122bin // 主函数 wwwlib // 公共库(自己) express.js mime.jsnode_modules //各种模块依赖 ...static //静态文件 css imgs js index.htmlviews //视图层,渲染模板 about.htmlapp.js //引入各种模块依赖及设置路由package.json //npm初始化文件 www123456789#!/usr/bin/env nodevar app = require('../app')var http = require('http')console.log(app)http.createServer(app).listen(8080)console.log('open http://localhost:8080') express.js123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119var url = require('url')var fs = require('fs')var path = require('path')var ejs = require('ejs')function express() { var tasks = [] var app = function(req, res){ addQuery(req, res) addSend(req, res) addRender(req, res, app) var i = 0 function next() { var task = tasks[i++] if(!task) { return } if(task.routePath === null || url.parse(req.url, true).pathname === task.routePath){ task.middleWare(req, res, next) }else{ next() } } next() } app.use = function(routePath, middleWare){ if(typeof routePath === 'function') { middleWare = routePath routePath = null } tasks.push({ routePath: routePath, middleWare: middleWare }) } app.data = {} app.set = function(key, value){ app.data[key] = value } app.get = function(key){ return app.data[key] } return app}express.static = function(staticPath){ return function(req, res, next){ var pathObj = url.parse(req.url, true) var filePath = path.resolve(staticPath, pathObj.pathname.substr(1)) console.log(filePath) fs.readFile(filePath,'binary', function(err, content){ if(err){ next() }else { res.writeHead(200, 'Ok') res.write(content, 'binary') res.end() } }) }}module.exports = expressfunction addQuery(req, res){ var pathObj = url.parse(req.url, true) req.query = pathObj.query}function addSend(req, res){ res.send = function(toSend){ if(typeof toSend === 'string'){ res.end(toSend) } if(typeof toSend === 'object'){ res.end(JSON.stringify(toSend)) } if(typeof toSend === 'number'){ res.writeHead(toSend, arguments[1]) res.end() } }}function addRender(req, res, app){ res.render = function(tplPath, data) { var fullpath = path.join(app.get('views'), tplPath) ejs.renderFile(fullpath, data, {}, function(err, str){ if(err){ res.writeHead(503, 'System error') res.end() }else { res.setHeader('content-type', 'text/html') res.writeHead(200, 'Ok') res.write(str) res.end() } }) }} index.html123456789101112131415161718<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>hello</title> <link rel="stylesheet" href="css/a.css"></head><body> <h1>hello world</h1> <img src="imgs/logo.png" alt=""> <form action="/search" method="POST"> <input type="text" name="username"> <input type="text" name="password"> <input type="submit" value="search"> </form> <script src="js/b.js"></script></body></html> about1234567891011121314151617181920<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>about</title></head><body> <h1><%= title %></h1> <dl> <dt>人物:</dt> <dd><%= people %></dd> <dt>日期:</dt> <dd><%= date %></dd> <dt>我的博客</dt> <dd><a href="<%= intro %>">点击查看</a></dd> </dl> </body></html> app.js12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455var express = require('./lib/express')var path = require('path')var bodyParser = require('body-parser')var urlencodedParser = bodyParser.urlencoded({ extended: false })var mimeType = require('./lib/mime')var app = express()app.use(urlencodedParser)app.use(mimeType)app.use(express.static(path.join(__dirname, 'static')))app.set('views', path.join(__dirname, 'views'))app.use(function(req, res, next) { console.log('middleware 1') next()})app.use(function(req, res, next) { console.log('middleware 12') next()})app.use('/hello', function(req, res){ console.log('/hello..') res.send('hello world')})app.use('/getWeather', function(req, res){ res.send({url:'/getWeather', city: req.query.city})})app.use('/search', function(req, res){ res.send(req.body)})app.use('/about', function(req, res){ res.render('about.html', { title: '头部', people: '张扬', date: '2018-1-1', intro: 'zy343134464@github.io' })})app.use(function(req, res){ res.send(404, 'haha Not Found')})module.exports = app package.json1234567891011{ "name": "step5", "version": "1.0.0", "main": "index.js", "license": "MIT", "dependencies": { "body-parser": "^1.17.2", "ejs": "^2.5.6", "mime-types": "^2.1.15" }}