Wednesday 17 May 2017

expressjs and module exports for routes with index

I'm trying to wrap my brain around using an index.js file to export my routes in an express-app.

./app.js

const server = require('express'),
      app    = server(),
      port   = process.env.PORT

require('./routes/index')(app)
app.listen(port)

./routes/index.js

function routes(app) {
    require('./test')(app)
}
module.exports = routes

./routes/test.js

function test(app) {
    app.get('/', function (req, res) {
        console.info('test')
        res.end('Hello, World!')
    })
}

module.export = test

Now, of course, when I execute ./app.js I get an error telling me that require( ... ) is not a function on ./routes/index.js:2

But I really can't seem to wrap my brain around this logic. Not the reason for my error, but how to bind modules together in this structure, while passing app to the modules.

The idea behind this structure (in case that's not obvious) is to create a system, where modules can be added and removed from the app by adding and removing them from the index file that belongs to each module, and then only require the index for each module-cluster (for example routes).



via Brian Emilius

No comments:

Post a Comment