开发者

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.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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜