nodejs中间件

来源:互联网 发布:网络音乐在线听歌曲 编辑:程序博客网 时间:2024/06/05 10:45

中间件使用的感悟


中间件主要是用于处理请求的模块化,每一个模块处理自己想要处理的请求,这个思想我觉得其实就像设计模式当中的责任链模式和代理模式,首先处理请求是链式的,每个中间件都会有一个use方法,在这个方法中接收一个返回函数

function(req,res,next)

这里依然有处理请求的req和res,但是在处理请求之后需要调用next方法传给下一个中间件,这里就像一个责任链模式。

下面给出演示代码
request-time.js
/** * Created by raid on 2016/11/7. *//** * 请求时间中间件 * * @param opts */module.exports = function (opts) {    var time = opts.time || 100;    return function (req, res, next) {        var timer = setTimeout(function () {            console.log('too long!', req.method, req.url);        }, time);        var end = res.end;        res.end = function (chunk, encoding) {            res.end = end;            res.end(chunk, encoding);            clearTimeout(timer);        };        next();    }}
demo.js
/** * Created by raid on 2016/11/7. */var connect = require('connect')    , time = require('./request-time');// var server = connect.createServer();var server = connect.createServer();/** * 记录请求情况 */server.use(connect.logger('dev'));/** * 实现时间中间件 */server.use(time({time : 500}));/** * 快速响应 */server.use(function (req, res, next) {    if ('/a' == req.url) {        res.writeHead(200);        res.end('Fast!');    } else {        next();    }});/** * 模拟触发中间件 */server.use(function (req, res, next) {    if ('/b' == req.url) {        setTimeout(function () {            res.writeHead(200);            res.end('Slow!');        }, 1000);        console.log("visit /b");    } else {        next();    }});server.listen(3000);
0 0
原创粉丝点击