Pasé muchas horas tratando de decodificar un búfer del servidor y no he podido averiguarlo.
Intenté eliminar JSON.parse() y sigo teniendo un error.
Estos son los datos enviados desde el backend donde convierto un objeto simple en un búfer y lo transformo en cadenas:
wss.clients.forEach((client) => { if (client.userID === contactID) { console.log(client.userID); client.send(Buffer.from(JSON.stringify(messageObj))); } });En la interfaz tengo un oyente:
ws.socket.addEventListener("message", async (message) => { const blobToText = await new Response(JSON.parse(message.data)).text(); alert(blobToText); console.log(blobToText) });Este es el error que estoy recibiendo:
[Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected identifier "object"] at components/Home/Home.js:38:12 in ws.socket.addEventListener$argument_1Cuando elimino el búfer del backend (solo usando stringify), obtengo esto en el cliente:
{"fields":{"consumerTag":"amq.ctag-LijiOI-nknkknjknj","deliveryTag":16,"redelivered":false,"exchange":"","routingKey":"messages"},"properties":{"headers":{}},"content":{"type":"Buffer","data":[123,34,114,101,97,100,34,58,102,97,108,115,101,44,34,116,105,109,101,83,101,110,116,34,58,49,54,52,54,48,55,52,50,54,52,55,54,53,44,34,109,101,115,115,97,103,101,34,58,34,102,101,114,102,101,114,102,34,44,34,117,115,101,114,73,68,34,58,52,55,44,34,99,111,110,116,97,99,116,73,68,34,58,52,55,125]}}Recibo esto cuando analizo ahora; ¿Cómo puedo convertir esto en el objeto de mensaje real?:
[ 101, 44, 34, 116, 105, 109, 101, 83, 101, 110, 116, 34, 58, 49, 54, 52, 54, 48, 55, 54, 56, 50, 48, 52, 58, 34, 101, 101, 102, 101, 119, 102, 34, 44, 34, 117, 115, 101, 114, 73, 68, 34, 58, 52, 55, 44, 34, 99, ]Solo deshazte del Buffer.
client.send(JSON.stringify(messageObj));en vez de
client.send(Buffer.from(JSON.stringify(messageObj)));