简体   繁体   English

node.js包括类文件

[英]node.js include class file

I got 2 files: 我有2个文件:

start.js start.js

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

conversation.js conversation.js

    var ConversationModule = new Object();

    ConversationModule.sayhello = function () {
    console.log("hello");
    };

    exports.ConversationModule = ConversationModule();

In start.js I cannot call the sayhello() method. 在start.js中我无法调用sayhello()方法。 I get following error 我得到以下错误

TypeError: object is not a function

I just don't get it why it doesn't work - I'm new to node :) 我只是不明白为什么它不起作用 - 我是节点的新手:)

You are trying to export ConversationModule as a function, which it is not. 您正在尝试将ConversationModule导出为函数,但实际上并非如此。 Use this instead: 请改用:

exports.ConversationModule = ConversationModule;

Since you're also assigning the variable as a property of exports , you'd have to call it like this: 由于您还将变量指定为exports属性,因此您必须将其称为:

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

If you don't want to do that, assign the object to module.exports : 如果您不想这样做,请将对象分配给module.exports

module.exports = ConversationModule;

And call it like this: 并称之为:

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

Given that you've named the file conversation.js, you probably intend to define solely the "conversation module" in that particular file. 鉴于您已将文件命名为conversation.js,您可能只打算在该特定文件中定义“对话模块”。 (One file per logical module is a good practice) In that case, it would be cleaner to change your export code, and leave your require code as you had it originally. (每个逻辑模块一个文件是一个好习惯)在这种情况下,更改导出代码并保留原始需求代码会更加清晰。

start.js start.js

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

conversation.js conversation.js

   var ConversationModule = new Object();

   ConversationModule.sayhello = function () {
     console.log("hello");
   };

   module.exports = ConversationModule;

Assigning something to module.exports makes this value available when you require the module with require . 当您需要带有require的模块时,为module.exports分配module.exports会使此值可用。

conversation.js: conversation.js:

var conversationModule = new Object();

conversationModule.sayhello = function () {
console.log("hello");
};

exports.conversationModule = conversationModule;

start.js: start.js:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM