Donatas Donatas - 26 days ago 7
Node.js Question

Can't create a server in an object node.js

I'm trying to put my server with its variables inside an object in order to keep my project clean, so I've created core.js file, which holds all server variables and looks like this:

module.exports =
{
express: require('express'),
http: require("http"),
app: this.express(),
server: this.http.createServer(this.app),
io: require('socket.io').listen(this.server),

runServer: function()
{
...........
}
};


I require this file inside my main file:

var core = require("./server/classes/core");


And when I try to run I get this error:

app: this.express(),

^

TypeError: this.express is not a function


What could possibly be the problem?

Answer

When you initialize the json as above in your code, they all execute at the same time and not one by one since they all belong to single line of execution.

Hence, all the below lines will be executed at the same time and not one by one.

{
    express: require('express'),
    http: require("http"),
    app: this.express(),
    server: this.http.createServer(this.app),
    io: require('socket.io').listen(this.server),

    runServer: function()
    {
        ...........
    }
};

So, at the time of execution of the line app: this.express(), this.express would be undefined.

Better you can define them in a function and assign to module.exports as below.

function Core() {
   this.express = require('express');
   this.http = require("http");
   this.app = this.express();
   this.server = this.http.createServer(this.app);
   this.io = require('socket.io').listen(this.server);

   .....
}

module.exports = new Core();

Another alternative is assigning them directly to the exports as below.

var express = require('express');
var http = require("http");
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

exports.express = express;
exports.http = http;
exports.app = app;
exports.server = server;
exports.io = io;
Comments