Reputation: 1597
I have server receiving data from a client [GPS Device]. I have problem presenting the data (i.e the results obtained from the client) in a readable format. Below are the things I have 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 full 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.
Upvotes: 7
Views: 20933
Reputation: 11
Do it like this
socket.on('data', function (data) {
var buff = Buffer.from(data);
But remember, lots of GPS devices use little-endian, so later you're going to have to decode the data as well.
Upvotes: 1
Reputation: 412
According to the documentation, you must specify an 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 could configure the socket to get the data in UTF-8, for example, with:
socket.setEncoding('utf8');
Upvotes: 10
Reputation:
Assuming the data in buffer is 7 bit ASCII,
console.log(data.toString('ascii'))
would resolve the problem.
Upvotes: 0