Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export functions Nodejs

Tags:

node.js

I'm using module.exports to export list of module. Below is my Models/Message.js

var msgModel = function()
{
    var getMsg = function() {
        return "Hello World";
    }
    return{
        getMsg : getMsg
    }
}
module.exports =  msgModel;

Below is my app.js

var msgModel = require('./Models/Message');
console.log(msgModel.getMsg());

It raised me error

console.log(msgModel.getMsg());
                 ^

I can't figure out the problem.

like image 952
nvtthang Avatar asked Sep 02 '26 11:09

nvtthang


1 Answers

You need to do console.log(msgModel().getMsg());. This is because msgModel is a function. I would suggest rewriting your msgModel like the example below instead to achieve the call you wanted.

var msgModel = {
    getMsg: function() {
        return "Hello World";
    }
};

module.exports = msgModel;
like image 102
Simon Mo Avatar answered Sep 05 '26 17:09

Simon Mo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!