Nodejs - load module once and use in many different files - javascript

My project directory looks something like this:
MyProject
-app.js
-routes
-routeone
-routetwo
Inside of my app.js file it looks like this:
var express = require('express');
var app = express();
var myModule= require('myModule');
app.use(myModule());
var routeone = require('./routes/routeone');
var routetwo = require('./routes/routetwo');
app.use('/routeone', routeone);
app.use('/routetwo', routetwo);
.
.
.
Each route file looks something like this:
var express = require('express');
var router = express.Router();
router.post('/', urlencodedParser, function(req, res, next) {
//Need to call myModule's createUser function. How do I call it here?
});
module.exports = router;
As you can see I have a dependency on the myModule module. I need to call a function in this module in every route.I may have many more routes in the future. I would like to avoid specifying this (calling require) in every single route file because in the future if I have hundreds of route and say the module now accepts options I would need to to every single file and since this manually. Is there a way to require it once (e.g in the app.js file) and then be able to use it everywhere?

You can write your route modules as such that during the time of creation(require call) they get their dependencies injected. I have added a sample below
route.js
module.exports = function(myModule, router, dep1, dep2){
router.post()
//use my module, dep1 and dep2
}
app.js
var mymodule = require('./myModule')
var dep1 = require('./dep1');
var dep2 = require('./dep2');
var router = express.Router();
var route = require('route')(mymodule, router, dep1, dep2);
Update - For returning router instance from route.js
route.js
module.exports = function(myModule, dep1, dep2){
router.post()
//other router invocations
return router
}
In app.js
var customRouter = require('route')(mymodule, router, dep1, dep2);
the customRouter will be an router instance since thats what is being returned by te invoked function in route.js

Related

grouping express routes into a single file

I trying to express routes into a single file using app.use
app.js
import express from 'express'
import testRouter from 'testRouter'
const app = express()
app.use('/testRouter', testRouter)
app.listen(3000)
testRouter.js
import express from 'express'
const router = express.Router
router.get("/page1", function (req, res){
res.send("test")
})
export default router
using module exports is a official ways to do it and it worked
But why doesn't the router definition inside a function work like bellow?
app.js
import express from 'express'
import testRouter from 'testRouter'
const app = express()
app.use('/testRouter', function (){
const router = express.Router()
router.get("/page1", function (req, res){
res.send("test")
})
return router
}))
app.listen(3000)
I don't believe the code inside app.use('/test/Router', function() { }) executes until a user has visited your test/Router page at least once. I'm also not sure if you can use a middleware ("use") without having an eventual terminal endpoint.
Because in the official documentation testRouter is an Object
app.use('/testRouter', Object)
You put the function
app.use('/testRouter', Functon)

Adding a routing file inside another routing file node.js

I want my routes to be like the following:
/
/business
/business/stuff1
/business/stuff2
/business/admin
for /business I want to have a separate file for the routing and functions.
and also for /business/admin I want to have a separate file for the routing and functions.
so what I did is:
app.js
//Business route
const business = require("./business/business");
app.use("/business", business);
This works fine - but when I add in business.js
//admin route
const admin = require("./admin");
app.use("/admin", admin);
I get 404 for some reason.
Depends on what you are exporing from business.js. It should be an instance of express.Router and you have to mount the /admin route on this instance. Example:
// business.js
const admin = require("./admin");
const businessApp = express.Router();
businessApp.use("/admin", admin);
module.exports = businessApp;

Express : router object and methods

I have
var router = express.Router();
router.get('/', function(req, res) {
//something
}
module.exports = router;
Is the router created, the get method executed and the router exported, or is it that the router is created, the method is define for this router (not executed) and the router is exported afterwards?
Second one. Router is created, method is defined and router is exported. That method will be executed when browser sends get request on '/' url, if you correctly require exported router.

separate(organize) express route

I separated routes for rest api like this. Is there better way to organize router ? or the way I am doing is fine?
app.js
app.use('/api/auth',auth);
app/controllers/auth/index.js
var express = require('express'),
router = express.Router(),
register = require('./register');
router.get('/',function(req,res,next){
console.log("api/auth");
res.send('api/auth');
next();
});
router.use('/register',register);
module.exports = router;
app/controllers/auth/register.js
var express = require('express'),
router = express.Router(),
rootPath = require('app-root-path'),
User = require(rootPath+'/app/models/user');
router.post('/',function(req,res,next){
console.log("api/auth/register");
next();
});
module.exports = router;
Building on swaraj'a answer, you should divide your project files into two folders lib and config. Please note that I'm giving you a generic structure this should be customised according to your project.
Config
It should contain all the configuration files for your project.
lib
It should basically have files like controller.js, routes.js, db-ops.js
controller.js contains and exports all functions required for your program logic.
routes.js contains and exports all the routes
db-ops.js intializes db connections and contains functions that define operations on database.
All these files should be required into your app.js which will reside in your projects root directory.
A typical project structure should look something like this:
lib
-routes.js
-controller.js
-db-ops.js
config
-config.json
app.js
You could create a routes.js which has all the separate routes.
Something like,
module.exports = function (app) {
app.use('/api/route1', require('path/to/route1'));
app.use('/api/route2', require('path/to/route2'));
};
Mount this routes in your main app.js.
require('path/to/routes')(app);
Shameless plug of an example, https://github.com/swarajgiri/express-bootstrap/blob/master/web/routes.js

Node.js router() usage confusion

why we need to use for example var route = Router(); since by default below simple example of express already fullful the usage of route :
var express = require('express'),
app = express();
app.get('/login',function(req,res,next){
//..something
});
The express.Router class can be used to create modular mountable route handlers. A Router instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”.
The following example creates a router as a module, loads a middleware in it, defines some routes, and mounts it on a path on the main app.
Create a router file named birds.js in the app directory, with the following content:
var express = require('express');
var router = express.Router();
// middleware specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
Then, load the router module in the app:
var birds = require('./birds');
...
app.use('/birds', birds);
The app will now be able to handle requests to /birds and /birds/about, along with calling the timeLog middleware specific to the route.

Categories