nodejs篇-手写koa中间件

微信扫一扫,分享到朋友圈

nodejs篇-手写koa中间件

koa-static

koa-static
可以处理静态资源,参数是静态资源文件夹路径,官方的实现包含了更多的参数配,具体可以查看 koajs/static

实现分析:

index.html
gzip
next
const fs = require("fs")
const path = require("path")
const mime = require("mime")
const zlib = require("zlib")
function static(dir) {
return async (ctx, next) => {
try {
let reqUrl = ctx.path
let abspath = path.join(dir, reqUrl)
let statObj = fs.statSync(abspath)
// 如果是文件夹,拼接上index.html
if (statObj.isDirectory()) {
abspath = path.join(abspath, "index.html")
}
// 判断路径是否准确
fs.accessSync(abspath);
// 设置文件类型
ctx.set("Content-Type", mime.getType(abspath) + ";charset=utf8")
// 客户端允许的编码格式,判断是否需要gzip压缩
const encoding = ctx.get("accept-encoding")
if (/\bgzip\b/.test(encoding)) {
ctx.set("Content-Encoding", "gzip")
ctx.body = fs.createReadStream(abspath).pipe(zlib.createGzip())
} else if (/\bdeflate\b/.test(encoding)) {
ctx.set("Content-Encoding", "bdeflate")
ctx.body = fs.createReadStream(abspath).pipe(zlib.createDeflate())
} else {
ctx.body = fs.createReadStream(abspath)
}
} catch (error) {
await next()
}
}
}
module.exports = static

koa-bodyparser

koa-bodyparser
可以处理POST请求的数据,将 form-data
数据解析到 ctx.request.body
,官方地址: koa-bodyparser

实现分析:

application/json
content-type
ctx.request.body
function bodyParser() {
return async (ctx, next) => {
await new Promise((resolve, reject) => {
let data = []
ctx.req.on("data", (chunk) => {
data.push(chunk)
})
ctx.req.on("end", () => {
let ct = ctx.get("content-type")
let body = {}
ctx.set("Content-Type", "application/json")
if (ct === "application/x-www-form-urlencoded") {
body = require("querystring").parse(Buffer.concat(data).toString())
}
if (ct === "application/json") {
body = JSON.parse(Buffer.concat(data).toString())
}
ctx.request.body = body
resolve()
})
ctx.req.on("error", (error) => {
reject(error)
})
})
await next()
}
}
module.exports = bodyParser

koa-router

koa-router
可以让koa像express一样控制路由,源码 koa-router
实现比较复杂,这里实现一个简单版本。

实现分析:

  • 先将请求保存到数组 middlewares
  • routes
    返回中间件函数,获取 ctx
    next
  • 从数组 middlewares
    过滤出 路径/方法
    相同的数据
  • 中间件处理,传入 ctx
    和封装后的 next
    ,处理结束才调用真正的 next
    方法
class Router {
constructor() {
// 保存中间件方法的数组
this.middlewares = []
}
get(path, handler) {
// get、post、delete、put这些方法都要处理,这里只实现get
this.middlewares.push({ path, handler })
}
compose(routes, ctx,next) {
// 派发每一个存储的中间件方法
const dispatch = (index) => {
// 处理完成才执行上下文的next
if (routes.length === index) return next();
// 将中间件的next包装成下个执行的dispath,防止多次执行上下文的next方法
routes[index].handler(ctx, () => dispatch(++index))
}
dispatch(0)
}
routes() {
return async (ctx, next) => {
// 过滤出相同的存储对象
let routes = this.middlewares.filter((item) => item.path === ctx.url)
this.compose(routes, ctx,next)
}
}
}
module.exports = Router;

koa-better-body

koa里面处理文件上传使用的是 koa-better-body
,这里需要保证表单中带有 multipart/form-data

<form action="/submiturl" method="POST" enctype="multipart/form-data">

下面是通过表单enctype为 multipart/form-data
提交后台拿到的数据:

------WebKitFormBoundaryfCunWPksjjur83I5
Content-Disposition: form-data; name="username"
chenwl
------WebKitFormBoundaryfCunWPksjjur83I5
Content-Disposition: form-data; name="password"
1234567
------WebKitFormBoundaryfCunWPksjjur83I5
Content-Disposition: form-data; name="avatar"; filename="test.txt"
Content-Type: text/plain
这里是文件内容
------WebKitFormBoundaryfCunWPksjjur83I5--

实现分析:

multipart/form-data
filename
ctx.request.fields
const fs = require("fs");
const path = require("path");
Buffer.prototype.split = function(sep){
let arr = [];
let offset = 0;
let len = Buffer.from(sep).length;
let current = this.indexOf(sep,offset);
while (current !== -1) {
let data=this.slice(offset,current)
arr.push(data);
offset = current+len;
current = this.indexOf(sep, offset)
}
arr.push(this.slice(offset));
return arr;
}
module.exports = function ({ uploadDir }) {
return async (ctx, next) => {
// 结果放到 req.request.fields
await new Promise((resolve, reject) => {
let data = []
ctx.req.on("data", (chunk) => {
data.push(chunk)
})
ctx.req.on("end", () => {
// multipart/form-data; boundary=----WebKitFormBoundaryvFyQ9QW1McYTqHkp
const contentType = ctx.get("content-type")
if (contentType.includes("multipart/form-data")) {
const boundary = "--"+contentType.split("=")[1];
const r = Buffer.concat(data);
const arr = r.split(boundary).slice(1,-1);
const fields = {};
arr.forEach(line=>{
let [head,body] = line.split("\r\n\r\n");
body = body.slice(0,-2); // 取出有效的内容
head = head.toString();
if(head.includes("filename")){
// 处理文件
// 请求头长度  = 总共的内容长度 - 头部长度 - 4个换行符长度
const filecontent = line.slice(head.length+4,-2);
const filenanme = head.match(/filename="(.*?)"/)[1] || uid();
const uploadPath = path.join(uploadDir, filenanme)
fs.writeFileSync(uploadPath, filecontent)
}else{
fields[head.match(/name="(.*?)"/)[1]] = body.toString();
}
})
ctx.request.fields = fields
}
resolve()
})
ctx.req.on("error", (error) => {
reject(error)
})
})
await next()
}
}
function uid(){
return Math.random().toString(32).slice(2);
}

微信扫一扫,分享到朋友圈

nodejs篇-手写koa中间件

日本《新解释·三国志》电影全新剧照 小栗旬曹操、胖版貂蝉亮相

上一篇

霸王别“机”

下一篇

你也可能喜欢

nodejs篇-手写koa中间件

长按储存图像,分享给朋友