11

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

1 Answer 1

15

If you have a UTF-16-encoded buffer, you can convert it to a UTF-8 Javascript 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')
Sign up to request clarification or add additional context in comments.

3 Comments

.toString('utf16le'); is particulary useful when sending accent letters through GSM SMS messages
Javascript strings are NOT in UTF-8.
@КонстантинВан you're right, see my edit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.