Including JavaScript class definition from another file in Node.js


Question

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?

1
91
3/15/2019 4:58:03 AM

Accepted Answer

You can simply do this:

user.js

class User {
    //...
}

module.exports = User

server.js

const User = require('./user.js')

// Instantiate User:
let user = new User()

UPDATE 2019

Since ES Modules became a standard, some authors are using them in their articles, what may be confusing, because Node.js doesn't allow to use ESM. Meantime Node.js has experimental support and requires a flag to make ESM work. Read about it in Node.js' ESM documentation.

Here it is an example of the same behavior for clarification:

user.js

export default class User {}

server.js

import User from './user.js'

let user = new User()

NOTE

Don't use globals, it creates potential conflicts in the future.

158
8/18/2019 10:27:26 PM

Using ES6, you can have user.js:

export default class User {
  constructor() {
    ...
  }
}

And then use it in server.js

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon