Data Processing Node.js

I have a server receiving data from a client [GPS device]. I have a problem with the presentation of data (i.e. results received from the client) in a readable format. Below are the things I tried.

Doing:

console.log(data)

I get

<Buffer d0 d7 3d 00 c4 56 7e 81>

Also tried

 console.log(data.toString())

But I get unwanted results: see below:

  A V~ 

Here is my complete code:

var net = require('net');
var fs = require('fs');

var server = net.createServer(function (socket) {
  console.log('Server started: Waiting for client connection ...');
  console.log('Client connected:port,address: '+socket.remotePort,      socket.remoteAddress);
  socket.on('data', function (data) {
        var date = new Date();
        var today = date.getDate()+'_'+date.getMonth();
        fs.appendFile(today+'_log.txt', data, function (err) {
          if (err) throw err;
            console.log(data.toString())

    });
 });
});

server.listen(my_port, my_ip);

Thanks for your input.

+4
source share
2 answers

According to the documentation, you must specify the encoding to get a string instead of a buffer:

Event: 'data'#
Buffer object
Emitted when data is received. The argument data will be a Buffer or String. Encoding of data is set by socket.setEncoding().

You can configure the socket to receive data in UTF-8, for example:

socket.setEncoding('utf8');
+6
source

Assuming the data in the buffer is 7 bits ASCII,

console.log(data.toString('ascii'))

.

0

Source: https://habr.com/ru/post/1527487/


All Articles