微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Middl 通用中间件

程序名称:Middl

授权协议: MIT

操作系统: 跨平台

开发语言: JavaScript

Middl 介绍

Middl 是采用JS编写的通用中间件。

安装

npm install --save middl

模块使用:

const middl = require('middl');
const app = middl();

// a sync middleware
app.use((input, output) => {
    output.prop = 1;
});

// an async middleware
app.use((input, output) => {
    // Faking a time consuming task...
    return new Promise(resolve => {
        setTimeout(() => {
            output.prop += 1;
            resolve();
        }, 10);
    });
});

// a time measuring logger:
app.use((input, output) => {
    var start = new Date();
  next()
        .then(() => {
            var ms = new Date() - start;
            console.log('Done in %s ms', ms);
        });
});
// or even prettier with generator functions:
app.use(function *(input, output) {
    var start = new Date();
    yield next();
    var ms = new Date() - start;
    console.log('Done in %s ms', ms);
});
// or when using Babel and async/await:
app.use(async (input, output) => {
    var start = new Date();
  await next();
    var ms = new Date() - start;
    console.log('Done in %s ms', ms);
});

// pass in the initial `input` and `output` objects
// and run the middleware stack:
app.run({val: 'hello'}, {})
    .then(output => {
        // output.prop === 2
    });

示例代码

const http = require('http');
const middl = require('middl');

// Make middl more Express like by using `url` as the property to match paths with:
const app = middl({pathProperty: 'url'});

// Adding all app.METHOD() functions à la Express:
http.METHODS.forEach(method => {
    app[method.toLowerCase()] = app.match({method});
});
// Also the app.all():
app.all = (path, fn) => {
    http.METHODS.forEach(method => {
        app[method.toLowerCase()](path, fn);
    });
    return app;
};

// A route handler for requests to: GET /test
app.get('/test', (req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('ok\n');
});
// A route handler for requests to: POST /test
app.post('/test', (req, res) => {
    res.writeHead(202, {'Content-Type': 'text/plain'});
    res.end('accepted\n');
});

// Make the middle app web server listen on port 3000:
http.createServer(app).listen(3000);

Middl 官网

https://github.com/joakimbeng/middl

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐