Reputation: 4519
I want to use some methods from other files. The only problem that I have is that the files using some other parameters already.
This is the file that I want to use. It is going to have some methods for my api calls. Models are my database models that I pass, and app is express() itself. The file is called test.
const express = require('express');
const router = express.Router();
module.exports = function (app, models) {
router.put('/', function (req, res) {
});
function test(){
};
return router;
};
Now I want to call the test method from this file. So I created this, but this is not working. I get the error test is not a function.
const testFile = require('test');
module.exports = function (app, models) {
router.get('/', function (req, res) {
testFile.test();
});
return router;
};
And this is my index.js:
app.use('/api/test', require('./routes/test.js')(app, models));
app.use('/api/main', require('./routes/main.js')(app, models));
What is the correct way to call method test from my other file?
Upvotes: 0
Views: 48
Reputation: 709
So you are exporting a function which in turn returns only route and not the function test. To access test function you need to do in this way,
module.exports = function(app, models) {
router.put('/', function (req, res) {
});
function test() {};
return {
router: router,
testFun: test
};
}
And in another file
const testFile = require('test')(app, models); // Correct path from current directory
module.exports = function (app, models) {
router.get('/', function (req, res) {
testFile.testFun();
});
return router;
};
Upvotes: 1