How to resolve Node js unicode conversion

Viewed 284

I am working on a UDP based client application. I have been facing the issue of Unicode(UTF - 8) conversation. I did convert decimal to Utf - 8 it was not given proper output. I got output like(À). if I send this output through UDP Client. The output is changed by(Ã). Why it was happing. Even those hex values also changed by C0 to C3.could anyone has to answer me? how to send Unicode in UDP communication?

 const dgram = require('dgram');
 const client = dgram.createSocket('udp4');
 const HOST = '192.168.43.232';
 const PORT = 5000;

 const message = String.fromCharCode(192);
 console.log(message); //<À>


client.send(message, 0, message.length, PORT, HOST, (err) => {
    if (err) throw err;
    console.log('UDP message sent to ' + message + ' ' + HOST + ':' + PORT); //UDP message sent to À 
    192.168.43.232:5000
    client.close();
 });


1 Answers

Node.js is working as expected. According to the docs, if the first argument to socket.send() is a string, it is automatically converted to UTF-8 buffer. The character 192 (U+00C0) is correctly converted to UTF-8 bytes 0xC380. The point you are missing here is that UTF-8 is not a single byte encoding; UTF-8 is a variable width character encoding. For all code points greater than 127, UTF-8 takes more than one byte. Therefore, in this case, the problem is with your client which is only considering the first byte of received message. You can see the UTF-8 Wikipedia page for more information.

Related