简体   繁体   English

node.js模块导出函数结构

[英]node.js module export function structure

I would like to expose a service as a module in node. 我想将服务作为节点中的模块公开。 Once required like: 一旦需要,如:

var MyService = require('../services/myservice');

I would like to be able to create an instance of the module and use its functions and properties like: 我希望能够创建模块的实例并使用其功能和属性,如:

var myService = new MyService();
var data = myService.getData();

I am having problems structuring the module using exports. 我在使用导出构建模块时遇到问题。 How should I setup the myservice.js code using exports? 我应该如何使用导出设置myservice.js代码?

//myservice.js    
module.exports = function(dependency){
   return {
      getData: function(){
         return 'The Data';
      },
      name: 'My Service'
   }
} 

I get the following error when trying to instantiate an instance using: 尝试使用实例化实例时出现以下错误:

var myService = new MyService();

TypeError: object is not a function TypeError:object不是函数

Let's say this is my Service.js module: 假设这是我的Service.js模块:

//Service.js
function Service(){}

Service.prototype.greet = function(){
    return "Hello World";
};


module.exports = Service;

Then in another module I can simply do: 然后在另一个模块中,我可以简单地做:

//another.js
var Service = require('./Service');

var service = new Service();
console.log(service.greet()); //yields "Hello World"

That works for me. 这对我行得通。 All you have to do is to export your Service constructor in the service module. 您所要做的就是在服务模块中导出Service构造函数。

--Edit-- - 编辑 -

To address your question in the comments. 在评论中解决您的问题。

Whatever you export with module.exports is what require will give you back. 无论你使用module.exports导出什么, require给你回复。 If you export a function, then you get a function back: 如果导出函数,则会返回一个函数:

//greet.js
module.exports = function(){
  return "Hello World";
};

Then you can do: 然后你可以这样做:

var greet = require('./greet');
console.log(greet()); //yields 'Hello World'

If you export an object, you get an object instance back: 如果导出对象,则会返回一个对象实例:

//greeter.js
module.exports = {
    greet: function(){
        return 'Hello World';
    }
};

Then you can do: 然后你可以这样做:

var greeter = require('./greeter');
console.log(greeter.greet()); //yields 'Hello World'

And logically if you export a constructor then you get a constructor back, which was my original example. 从逻辑上讲,如果你导出一个构造函数,那么你会得到一个构造函数,这是我原来的例子。

So, if you use your approach, you get back a function, not a constructor, unless, of course, your exported function is actually your constructor. 所以,如果你使用你的方法,你会得到一个函数,而不是一个构造函数,除非你导出的函数实际上是你的构造函数。 For instance: 例如:

//greeter.js
module.exports = function Greeter(){
    this.greet = function(){
        return 'Hello World';
    };
};

And then you can do the same thing I originally did: 然后你可以做我原来做的事情:

var Greeter = require('./Greeter');
var greeter = new Greeter();
console.log(greeter.greet());

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

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