Martin Martin - 5 months ago 17
Javascript Question

Including Javascript class definition from another file in Node.js

I'm writing a simple server for Node.js and I'm using my own class called

User
which looks like:

function User(socket) {
this.socket = socket;
this.nickname = null;

/* ... just the typical source code like functions, variables and bugs ... */

this.write = function(object) {
this.socket.write(JSON.stringify(object));
}
};


and then later in the process I'm instantiating it a lot:

var server = net.createServer(function (socket) {
/* other bugs */
var user = new User(socket);
/* more bugs and bad practise */
});


Can I move my
User
class definition to another javascript file and "include" it somehow?

Answer

And even you can simply do this

user.js

module.exports = function User() {
    //...
}

server.js

var User = require('./user.js');
var user = new User();

P.S. And don't use globals it's not true way because it could become great problem in the future.

Comments