0

I have been reading up on this and apprently there are more ways to export a module in node.js.

One of the simple things you can do with modules is to encapsulate functions within a file like so:

module.exports = {
  sayHelloInEnglish: function() {
    return "HELLO";
  },

  sayHelloInSpanish: function() {
    return "Hola";
  }
};

However i would like to create some more dirverse modules and so ive created the following user module:

    var UserModule = function (socket) {
    var userList = [];

    socket.on('userData', function (userDetails) {
        userDetails.socket = socket;
        userList[userDetails.id] = userDetails
    });

    socket.on('getActiveUsers', function () {
        socket.emit('activeUsers', userList);
    });

    function helloWorld (){
        console.log('hello world');
    }

};

module.exports = function (socket) {
    return new UserModule(socket);
};

now i am requireing this module in my io instance:

    io.on('connection', function (socket) {
    var my_user = userList.id;
    socket.on('userData', function (userDetails) {
        userDetails.socket = socket;
        userList[userDetails.id] = userDetails
    });


    var userModule = require('./costum_modules/UserModule.js')(socket);
    userModule.helloWorld();
    var chatModule = require('./costum_modules/ChatModule.js')(socket, userModule);
    var cacheModule = require('./costum_modules/CacheModule.js')(socket, userModule);
    var notificationModule = require('./costum_modules/NotificationModule')(socket, sequelize, userList);

});

The socket.on methods are working fine in my UserModule however i am unable to call the function helloWorld. if i try i get the following error:

userModule.helloWorld is not a function

So my question is, is what i am trying to do even possible? how am i able to store objects, functions ect in a module for later use?

1 Answer 1

1

function helloWorld is essentially a private function for use within your userModule.

You can make it public by changing the function declaration to the following:

this.helloWorld = function (){
    console.log('hello world');
}
Sign up to request clarification or add additional context in comments.

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.