Node.js export structure structure

I would like to provide the service as a module in node. As soon as required:

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

I would like to be able to instantiate a module and use its functions and properties, for example:

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

I'm having problems structuring a module using export. How do I customize myservice.js code using export?

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

When I try to instantiate an instance, I get the following error:

var myService = new MyService();

TypeError: object is not a function

+4
source share
1 answer

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 just do:

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

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

This works for me. All you have to do is export the constructor Serviceto the service module.

- Edit -

.

module.exports, , require . , :

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

:

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

, :

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

:

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

, , , .

, , , , , , . :

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

, :

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

Source: https://habr.com/ru/post/1542828/


All Articles