Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I get a <Buffer…/> when I console.log message sent by user using Websocket

index.html :

<script>

    let ws = new WebSocket('ws://localhost:8000');
    ws.onopen = (event) => {
        ws.send('Hola from client Side');
    }
    ws.onmessage = (event) => {
        console.log(event);
    }

</script>

server.js :

const http = require('http');
const websocket = require('ws');

const server = http.createServer((req, res) => {
    res.end("hello")
});

const wss = new websocket.Server({ server });

wss.on('connection', (ws, req) => {
    ws.send('Hello from the websocket server');
    ws.on('message', (msg)=>{ 
        console.log(msg)//---->>> THIS IS LOGING A BUFFER OBJECT, when I am expecting to log 'Hola from client Side'
    })
});

server.listen(8000);

The console.log in the server is returning:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<Buffer 48 65 6c 6c 6f 20 66 72 6f 6d 20 63 6c 69 65 6e 74 20 53 69 64 65>

But what I am sending from the client side is

ws.send('Hola from client Side');

Any help is appreciated.

>Solution :

You need to use the .toString() function to convert the buffer to a string.

Like this:

console.log(msg.toString())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading