Search code examples
javascriptnode.jstcpbufferserversocket

how to convert binary to string (big endian) format


ı have a tcp socket and ı try to get binary data from there and convert it to string by node js

here is my code

const Net = require('net');
const port = 4000;
const host = '0.0.0.0';

const client = new Net.Socket();
client.connect({ port: port, host: host }), function() {
    console.log('TCP connection established with the server.');

    client.write('Hello, server.');
};
client.on('data', function(chunk) {
    console.log(chunk);
    
    client.end();
});

client.on('end', function() {
    console.log('Requested an end to the TCP connection');
}); 

and the output is

<Buffer 82 44 53 53 76 57 37 56 4c 6d 62 ed 14 00 00 00 00 00 00 00 00 00 00 00 00 4c 05 e5 58 00 00 00 00 e1 8f 80>


Solution

  • I think you just missing to set encoding. I think all you need to do is to client.setEncoding("utf8") after you declare it, and it should work. If not, then you should check out a Buffer api and play with transforming your binary data into different formats.

    Here's the useful references:

    https://nodejs.org/api/net.html#event-data

    https://nodejs.org/api/net.html#socketsetencodingencoding

    https://nodejs.org/api/buffer.html