Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node encode and decode utf-16 buffer

im working on a javascript/nodejs application that needs to talk with a C++ tcp/udp socket. It seems like I get from the old C++ clients an utf16 buffer. I didn't found a solution right now to convert it to a readable string and the other direction seems to be the same problem.

Is there a easy way for this two directions?

Nice greetings

like image 852
user2244925 Avatar asked Nov 04 '16 08:11

user2244925


People also ask

How do I decode Buffer data in node JS?

In Node. js, the Buffer. toString() method is used to decode or convert a buffer to a string, according to the specified character encoding type. Converting a buffer to a string is known as encoding, and converting a string to a buffer is known as decoding.

How do I encode a Buffer in Node JS?

var buf = new Buffer("Simply Easy Learning", "utf-8"); Though "utf8" is the default encoding, you can use any of the following encodings "ascii", "utf8", "utf16le", "ucs2", "base64" or "hex".

How do you convert a Buffer to a string value in node JS?

Buffers have a toString() method that you can use to convert the buffer to a string. By default, toString() converts the buffer to a string using UTF8 encoding. For example, if you create a buffer from a string using Buffer. from() , the toString() function gives you the original string back.

How do you decode a binary Buffer to an image in node JS?

let binary = Buffer. from(data); //or Buffer. from(data, 'binary') let imgData = new Blob(binary. buffer, { type: 'application/octet-binary' }); let link = URL.


1 Answers

If you have a UTF-16-encoded buffer, you can convert it to a UTF-8 string like this:

let string = buffer.toString('utf16le');

To read these from a stream, it's easiest to use convert to string at the very end:

let chunks = [];
stream.on('data', chunk => chunks.push(chunk))
      .on('end',  ()    => {
        let buffer = Buffer.concat(chunks);
        let string = buffer.toString('utf16le');
        ...
      });

To convert a JS string to UTF-16:

let buffer = Buffer.from(string, 'utf16le')
like image 84
robertklep Avatar answered Sep 21 '22 04:09

robertklep