node.js module export function structure

javascript, node.js

Solution

Let's say this is my Service.js module:

//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.

--Edit--

To address your question in the comments.

Whatever you export with `module.exports` is what `require` will give you back. 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());

Problem

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 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

Original source