0

I'm working with an Enfora MT4000 device. The device sends data to tcp or udp server when certain event has occurred. Data can be send in binary or ASCII format, but I need to use binary.

Enfora device is configured with AT commands like this:

AT$EVENT=14,0,7,1,1
AT$EVENT=14,3,52,14,1578098

When I configure the device with ASCII, the server receives data in this format:

r        13    0    0 $GPRMC,211533.00,A,3321.856934,S,07040.240234,W,0.0,0.0,120514,2.3,W,A*2B

But, when I use binary, the data looks like this:

$2K�  �Dk����a�H

Anyone knows how Node.js can convert binary data from a socket? I'm trying to do this with a very simple script.

// server
require('net').createServer(function (socket) {
    console.log("connected");
    socket.setEncoding(null);
    socket.on('data', function (data) {
        console.log(data.toString());
    });
})

.listen(3041);

thanks.

1 Answers1

2

The data argument in your 'data' event handler is already a Buffer. By calling data.toString() you are converting that Buffer to a (UTF-8 by default) string. You're probably better off keeping it as a Buffer and using that if you need the original binary data.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • It is possible to convert the buffer's data to `string` with javascript? – Danilo Aburto Vivians May 15 '14 at 20:20
  • ASCII is a subset of UTF-8, so the default buffer.toString() should return the correct results – levi May 15 '14 at 21:42
  • @DaniloAburto It's not clear what kind of string you're expecting. If the data is part binary and part string, you can use data.[toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) with both encoding and start and end arguments. – mscdex May 15 '14 at 21:47
  • I was confused with the data type. I resolved the problem by reading buffer directly (00 24 00 05 02 00...). Thanks to @mscdex. – Danilo Aburto Vivians May 16 '14 at 04:11
  • thanks for the answer, can you give an example of reading binary from a Node.js Buffer object? Having trouble finding information on that. – Alexander Mills Jan 18 '17 at 09:26