In this article I will show how you can manage your routes in a separate file from app.js. It also demonstrates more generally how adding modules to your applications works in node.js.
Introduction
In this article I will create a simple route in a route.js file and reference it from my app.js. This will demonstrate how to keep the code separated and easier to manage.
The example application
This is a very simple express example with only two routes – the root of the app which says “Hi I am the root” and a second one which says “I am a new route”.
The initial app is a very basic app created using express.
// Startup Express App var express = require('express'); var app = express(); var http = require('http').Server(app); http.listen(3000); // handle HTTP GET request to the "/" URL app.get('/', function(req, res) { res.write("Hi I am the root") res.end(); })
Which then produces the following simple page
New routes.js
I created the following file routes.js which will display a message when going to /marky
module.exports = function(app) { app.get('/marky', function(req, res) { res.write("I am a new route") res.end(); }); }
mobile.exports is node.js specific code which allows for code includes in this very manner. For more on this check out this article. Notice that (app) is passed to the function so that it properly scoped to the original code.
Back in the app.js we add a single line to require this new library and that’s it.
// Startup Express App var express = require('express'); var app = express(); var http = require('http').Server(app); //include other libraries var routes = require('./routes')(app); //This is the extra line http.listen(3000); // handle HTTP GET request to the "/" URL app.get('/', function(req, res) { res.write("Hi I am the root") res.end(); })
Conclusion
More fundamentally than this simple example, this is the core of how node modules (including express) work. When you “require” express or http or any other module within your node application, this is how it is put together. Kinda cool 🙂
[…] How to add a NodeJS Express route in a separate file In this article I will show how you can manage your routes in a separate file from app.js. It also demonstrates more generally how adding modules to your applications works in node.js. Introduction In this article I will create a simple route in a route.js file and reference it from my app.js. This will demonstrate how […] […]
This was a great help. Thanks.
It works for me, thanks !
hi,
how to send arguments form main.js file : var routes = require(‘./routers’)(app);
and how will be receiving in router.js file :
module.exports = function(app) {
app.get(‘/’,function (request, response){
response.render(‘layouts\\index’,{
data : data,
});
});
}
Not working for post calls. Body missing 😥