0

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?

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Everything worked out on both ways, though I like first one more. Didn't knew that everything is being defined at the same time in objects...
@Donatas, great mate and just upvote it if you like it :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.