How to export all routes in Express?

前端 未结 3 1483
南方客
南方客 2021-02-02 03:52

I have an NodeJS Express app that is getting really big in just one file (app.js).

I want to export all my routes into a single, external file, say ./lib/routes.j

3条回答
  •  情书的邮戳
    2021-02-02 04:25

    using glob you can export all routes on directory for example '/routes':

    npm i --save glob

    
        // *** /routes/index.js file ***
    
        const express = require('express')
        const Router = express.Router
        const router = Router()
        const glob = require('glob')
    
    
        /**
         * options ignore files inside routes folder
         */
        const options = {
            ignore: [`${__dirname}/_helpers.js`, `${__dirname}/index.js`]
        }
    
        /**
         * read all files on current directory and export routes as lowercase of the filename
         * example 'routes/Products.js' route will be access by '/products'
         */
        const routes = 
            glob.sync(__dirname + '/*.js', options)
                .map(filename => {
                    const arr = filename.split('/')
                    let name = arr.pop();
                    name = name.replace('.js', '')
                    return {
                        path: `/${name.toLowerCase()}`,
                        router: require(`${filename.replace('.js', '')}`)
                    }
                })
                .filter(obj => Object.getPrototypeOf(obj.router) == Router)
                .forEach(obj => router.use(obj.path, obj.router))
    
    
        module.exports = router;
    

    then

    on app.js

    // app.js file
    
    const express = require('express')
    const routes = require('./routes')
    
    
    const app = express()
    
    app.use('/api', routes)
    
    

提交回复
热议问题