Can i use ws.onmessage in node.js server?

15 views Asked by At

I have websocket server running on node.js server. I'm using ws package to create websocket server. I added the event listener for message event in the server like below and I receive the message in buffer type

ws.on('message', (message) => {
//logics. here the message is buffer.
});

I need to get data from the message so that I need to parse the message. To parse the message, I need to convert that into string and then to js object. We can parse the buffer directly and that also will convert it into string first and then to js object.

I noted there is one another event listener for message: onmessage. I added that one. It fits for my use case. Previously I used uws package where it will receive the message as string. If ws receive the message as string, I don't need to convert the buffer to string. i can avoid one step here. The Server will receive lots of messages so that I concern about the buffer to string and the string to object conversion.

ws.onmessage = (event) => {
// logics. here the event.data is string
}

Can I use ws.onmessage instead of ws.on('message')? Is there any standard like we should use this ws.onmessage only on browser? If I use ws.onmessage instead of ws.on('message') , will it cause any issue? Could anyone please help me?

Thanks in advance!

0

There are 0 answers