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

Time:01-02

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:

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

CodePudding user response:

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

Like this:

console.log(msg.toString())
  • Related