Fez Vrasta
Fez Vrasta

Reputation: 14835

Split express app in submodules

I've this app:

// Some modules
var express = require("express");
var ... = require("...");
var ... = require("...");

// Here will go the db
var db;

// Init express
var app = express();

// Express configuration
app.use(...);
app.use(...);

// Routes
app.get("/", function() {});
app.get("/api/v1/a", function() {});
app.get("/api/v1/b", function() {});

// Connect to the db, store it in "db" and then set the port of the app
MongoClient.connect("mongodb://localhost/db", function(err, connection) {
  db = connection;
  app.listen(3000);
});

I'd like to split this app in multiple files, for example I'd like to move the api routes into an api.js file.

I've tried with this api.js:

function(app, db) {
  app.get("/api/v1/a", function() {});
  app.get("/api/v1/b", function() {});
}
module.exports = api;

And then use it with:

var api = require("./api");
api(app, db);

But the routes defined inside it are not executed, how can I do?

Upvotes: 0

Views: 829

Answers (2)

Fez Vrasta
Fez Vrasta

Reputation: 14835

Ok found a solution:

api.js:

module.exports = function (app, db) {
    app.get("/api", function(req, res) { ... });
}

index.js:

require("./api")(app, db);

This way it works flawlessly.

Upvotes: 2

Simon H
Simon H

Reputation: 21005

Try:

var api = require("./api");
app.use('/', api)

Upvotes: 2

Related Questions