2

PROBLEM

I want to receive data from a device using IP Address via NodeJs. But I received the following data:

funny characters

What I've Tried

This is the code that I've been able to get, which still produces the problem I described above.

var app = require('http').createServer(handler);
var url = require('url') ;
var statusCode = 200;

app.listen(6565);

function handler (req, res) {
 var data = '';

req.on('data', function(chunk) {
  data += chunk;
});

req.on('end', function() {
console.log(data.toString());
fs = require('fs');
fs.appendFile('helloworld.txt', data.toString(), function (err) {
  if (err) return console.log(err);
});
});

res.writeHead(statusCode, {'Content-Type': 'text/plain'});
res.end();
}

And below is the result I received for console.log(req.headers)

req.headers console

So my question is, how do I decode the data? and anyone know what type of data are they?

Amalina Aziz
  • 204
  • 2
  • 18

1 Answers1

1

Use Buffers to handle octet streams.

function handler (req, res) {

    let body=[];

    req.on('data', function(chunk) {
        body.push(chunk);
    });


     req.on('end', function() {
        body = Buffer.concat(body).toString('utf8');
    ...
Aakash Verma
  • 3,705
  • 5
  • 29
  • 66
  • Try this and let me know :/ – Aakash Verma Jul 20 '17 at 09:12
  • `chunk` is already a Buffer. Also, `Buffer.concat` requires an array of Buffer instances, not a single one, and should really be called in the `end` handler. – robertklep Jul 20 '17 at 09:12
  • @robertklep Thanks a lot! I have got so rusty. – Aakash Verma Jul 20 '17 at 09:15
  • Lastly: because the response is `application/octet-stream`, it's likely to be a binary format, so calling `toString()` on it may mangle it (however, it seems that OP doesn't know what the format of the data is, so it may be _anything_). – robertklep Jul 20 '17 at 09:17
  • @AmalinaAziz Why are you suggesting that edit? Did the previous one work for you? – Aakash Verma Jul 20 '17 at 09:19
  • @AakashVerma missing ). but the buffer one didn't work. – Amalina Aziz Jul 20 '17 at 09:21
  • @robertklep Isn't toString() actually specified by the Buffer class to do that? I agree that the encoding is optional. – Aakash Verma Jul 20 '17 at 09:21
  • @AakashVerma with `toString()`, you're telling Node to try and convert the binary data to a (UTF-8-encoded) string, but it may not be a string, or UTF-8-encoded, at all. – robertklep Jul 20 '17 at 09:22
  • @AmalinaAziz what exactly isn't working? We can't help you with decoding the data properly if you don't know what it actually is. – robertklep Jul 20 '17 at 09:23
  • @robertklep Okay but if we are able to get a string representation of it, we can later know what to do. Aziz doesn't know what data format or what data he is receiving. – Aakash Verma Jul 20 '17 at 09:59
  • @AakashVerma in that case, you want to use `toString('binary')`, so Node will not try to convert it to UTF-8. – robertklep Jul 20 '17 at 10:01