Call functions between nodejs modules

I have two modules:

var client  = require('./handlers/client.js');
var server  = require('./handlers/server.js');

server.createClient()

      

client.js

var client = function(){
    console.log("New client");
}

exports = module.exports = client;

      

server.js

var server = {
   createClient: function() {
       var newClient = new client();
   }
}

   exports = module.exports = server;

      

By doing this, the server module says the client function is undefined.

How can I get this to work?

+3


source to share


1 answer


If you want to call client()

in server.js you will need to include this line:

var client  = require('./client.js');

      

in the server.js file, so that's client

defined there, so the whole sequence in server.js will look like this:

var client  = require('./client.js');
var server = {
   createClient: function() {
       var newClient = new client();
   }
}

exports = module.exports = server;

      



You must require()

use every module in every module.


The module structure is designed to make each module stand on its own. This means that each module has its own namespace and, by default, does not have access to the namespace of other modules. So when you need to access something from another module, you must either use require()

to access it, or you must call a function in another module (you have required()

in) and access through that module.

+2


source







All Articles