ZhangYang's Blog

Node.js后端服务器框架

作用

1
2
3
4
本地开启服务器
根据路径mock数据
读取静态文件
支持模板引擎渲染

目录结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bin // 主函数
www
lib // 公共库(自己)
express.js
mime.js
node_modules //各种模块依赖
...
static //静态文件
css
imgs
js
index.html
views //视图层,渲染模板
about.html
app.js //引入各种模块依赖及设置路由
package.json //npm初始化文件

www

1
2
3
4
5
6
7
8
9
#!/usr/bin/env node
var app = require('../app')
var http = require('http')
console.log(app)
http.createServer(app).listen(8080)
console.log('open http://localhost:8080')

express.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
var 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 = express
function 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.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!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>

about

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!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.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var 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.json

1
2
3
4
5
6
7
8
9
10
11
{
"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"
}
}