Question

I think it is cool that I can use following to create instance of httpServer:

var express = require("express"),
  app = express(),
  httpServer = require("http").createServer(app);

However if I make my own server class which should return instance of itself how I can do it?

Currently I have for example following:

server.js:

var Server = function() {
  this.someVar = 1;
};

Server.prototype.someMethod1 = function() {
  console.log("1");
};

Server.prototype.someMethod2 = function() {
  console.log("2");
};

module.exports = Server;

And I use it like this:

var Server = require("./app/server"),
    server = new Server();

Clumsy? I want it like this:

var server = require("./app/server").createServer();

// then, do what ever I want with server instance
server.someMethod1();

Thnx for the help!

Was it helpful?

Solution

You can use:

server.js

var Server = function() {
  this.someVar = 1;
};

Server.prototype.someMethod1 = function() {
  console.log("1");
};

Server.prototype.someMethod2 = function() {
  console.log("2");
};

module.exports.createServer = function () {
   return new Server();
};

And to use it:

var server = require("./app/server").createServer();

If you want to be able to create instances of your server in "express fashion" you can use:

module.exports = function () {
   return new Server();
};

And to use that:

var server = require("./app/server")();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top