I have a module in NodeJS which has the following definition:
var express = require('express');
var router = express.Router();
function myFunction(){
//do some stuff
};
router.get('/url', function(req, res, callback) {
var data = myFunction();
res.render('index', {
item: data
});
});
module.exports = router;
Run Code Online (Sandbox Code Playgroud)
I want it to be called in both ways:
HTTP petition:
http://localhost:3090/url
Run Code Online (Sandbox Code Playgroud)
As a function in another module:
var myModule = require('myModule');
var data = myModule.myFunction();
Run Code Online (Sandbox Code Playgroud)
I can access the module by HTTP in the way shown above. However, I don't know how to export myFunction
to be used in another module. I have tried the following without any success:
router.myFunction = myFunction;
module.exports = router;
Run Code Online (Sandbox Code Playgroud)
And:
module.exports = router;
module.exports.myFunction = myFunction;
Run Code Online (Sandbox Code Playgroud)
How could I solve this problemn? Thank you very much in advance
you can make these changes
use exports to expose multiple functions
exports.router = router;
exports.myFunction = myFunction;
Run Code Online (Sandbox Code Playgroud)
for including them both in other file(path to myModule can vary as per your structure) you can now include them as
var routes= require('./myModule').router;
var myfunction = require('./myModule').myFunction;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
410 次 |
最近记录: |