Martin Martin - 1 year ago 132
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

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) {

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
class definition to another javascript file and "include" it somehow?

Answer Source

And even you can simply do this


module.exports = function User() {


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download