开发者

Including JavaScript class definition from another file in Node.js

开发者 https://www.devze.com 2023-03-26 19:42 出处:网络
I\'m writing a simple server for Node.js and I\'m using my own class called User which looks like: function User(socket) {

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.nicknam开发者_JS百科e = 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?


You can simply do this:

user.js

class User {
  //...
}

module.exports = User // 
0

精彩评论

暂无评论...
验证码 换一张
取 消