I am a beginner of Node.js.
Recently i would like to build a modulize system based on es6-class.
I am trying to wrap ws module to a class, and here is the prototype of my code:
const WebSocket = require('ws')
export default class WebSocketServer {
constructor(port = 9876) {
this.wss = new WebSocket.Server({
port,
perMessageDeflate: false
})
this.wss.on('connection', (function _connection(ws) {
this.connection(ws)
}).bind(this))
}
connection(ws) {
return new Promise(function (resolve, reject){
ws.on('message', function _incoming(message){
console.log('received: %s', message)
})
ws.send('Welcome!', function ack(err){
if(err) {
reject(`Connection error: ${err}`)
}
else {
resolve('Connection created.')
}
})
})
}
}
Few question:
1. I wonder my logic is right?
2. Is there a simple way to instead bind 'this' to callback function?
Thanks!