# express 动态加载route与使用自定义回调和通用回调

server.js

```javascript
import express from 'express';
import http from 'http';
import router from './router';

const app = express();
const service = http.createServer(app);

app.use('/', router);

service.listen(3000);
```

router.js

```javascript
import express from 'express';
import fs from 'fs';
import path from 'path';
import requestHandler from '../requestHandler';

let api = express.Router();

// 使用path，绝对路径
fs.readdirSync(path.join(__dirname, '/routeMap'))
  .filter(function (filename) {
    return filename !== 'index.js' && filename.slice(-3) === '.js';
  })
  .forEach(function (filename) {
    const servicename = filename.split('.js')[0];
    let filepath = path.join(__dirname, '/routeMap/', filename);
    let service = require(filepath);
    Object.keys(service).map((key, index) => {
      service[key].map((path) => {
        // 自定义回调
        if (typeof path === 'object') {
          api[key](path.url, path.handler);
        } else {
        // 使用通用封装回调
          api[key](path, requestHandler);
        }
      });
    });
  });

export default api;

```

routerMap/servicename.js

```javascript
module.exports = {
    get: ['/api/get'],
    post: ['/api/post'],
    delete: [],
    patch: [],
    put: [
        {
            url: '/api/put',
            handler: function(req, res) {
                res.send(200)
            }
        }
    ]
}
```

&#x20;requestHandler.js

```javascript
// define your request handler
```
