2

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.

4 Answers 4

5

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

Comments

2

You could do something like this:

var msg = new msgModel();
console.log(msg.getMsg());

Comments

2

You should export a function and invoke it in the main app.js

for example:

app.js

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

Message.js

var getMsg = function(){
    console.log("Hello World!");
};

module.exports = getMsg;

Comments

0

You could write it this way in order to group more functions:

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

then you could use:

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

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.