1

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;

I want it to be called in both ways:

HTTP petition:

http://localhost:3090/url

As a function in another module:

var myModule = require('myModule');
var data = myModule.myFunction();

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;

And:

module.exports = router;
module.exports.myFunction = myFunction;

How could I solve this problemn? Thank you very much in advance

1
  • how about module.exports.router = router; module.exports.myFunction = myFunction; ? sounds more like you'd want to split the two in two seperate modules though Commented Dec 3, 2014 at 16:27

2 Answers 2

5

you can make these changes

use exports to expose multiple functions

exports.router = router; 
exports.myFunction = myFunction;

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;
Sign up to request clarification or add additional context in comments.

2 Comments

function myFunction() will work just fine. Explicit assignment isn't necessary.
My pleasure, great to hear it helped you
1

Another way is to also sum up everything you're exporting at the end of the module - basically construct the exports object:

module.exports = {

    myFunction: myFunction,
    router: router,
    someConstant: 42,
    anotherValue: calculateThisValue()
}

At any time, module.exports is a global per-file object you get when you require that file. If you put nothing there, it'll be undefined. If you make it a function, then it'll be a function. If you make an object literal like above, you get an object. You can also export primitives, like dates, arrays, or whatever else you may think of.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.