Node.js includes a class file

I have 2 files:

start.js

var ConversationModule = require('./src/classes/conversation/Conversation.js'); ConversationModule.sayhello(); 

conversation.js

  var ConversationModule = new Object(); ConversationModule.sayhello = function () { console.log("hello"); }; exports.ConversationModule = ConversationModule(); 

In start.js, I cannot call the sayhello () method. I get the following error

 TypeError: object is not a function 

I just don't understand why this is not working - I'm new to node :)

+7
javascript include
source share
3 answers

You are trying to export a ConversationModule as a function that it is not. Use this instead:

 exports.ConversationModule = ConversationModule; 

Since you also assign the variable as the exports property, you should call it like this:

 var ConversationModule = require('./file').ConversationModule; ConversationModule.sayhello(); 

If you do not want to do this, assign a module.exports object:

 module.exports = ConversationModule; 

And name it as follows:

 var ConversationModule = require('./file'); ConversationModule.sayhello(); 
+10
source share

Given that you named the chat.js file, you probably intend to define only the β€œtalk module” in this particular file. (One file per logical module is good practice) In this case, it would be easier to change the export code and leave the required code as you originally had it.

start.js

 var ConversationModule = require('./src/classes/conversation/Conversation.js'); ConversationModule.sayhello(); 

conversation.js

  var ConversationModule = new Object(); ConversationModule.sayhello = function () { console.log("hello"); }; module.exports = ConversationModule; 

Assigning something to module.exports makes this value available if you need a module with require .

0
source share

conversation.js:

 var conversationModule = new Object(); conversationModule.sayhello = function () { console.log("hello"); }; exports.conversationModule = conversationModule; 

start.js:

 var conversationModule = require('./src/classes/conversation/Conversation.js').conversationModule; conversationModule.sayhello(); 
0
source share

All Articles