Exporting functions/ objects in a NodeJS + Express route file
In general NodeJS router files looks like following, where we create router
and add endpoints to it and export the router
.
api.js
var express = require('express');
var router = express.Router();
router.get('/ping', (req, res) => {
res.send('pong');
}));
module.exports = router;
and in the server.js
or index.js
file we wire it using the following code
index.js
var express = require('express');
var app = express();
app.use('/api', require('./api.js'));
But in some cases, we may want to return functions or objects from the same router file, we can achieve that using the following code.
api.js
var express = require('express');
var router = express.Router();
let barData = {
a: 1,
b: 2
}
function fooFunc(){
}
router.get('/ping', (req, res) => {
res.send('pong');
}));
module.exports = {
router,
fooFunc,
barData
};
index.js
var express = require('express');
var app = express();
app.use('/api', require('./api.js').router);
// using the data
console.log(require('./api.js').barData);
// using the functon
require('./api.js').fooFunc();