Amalina Aziz
Amalina Aziz

Reputation: 204

NodeJs Decode to readable text

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?

Upvotes: 2

Views: 980

Answers (1)

Aakash Verma
Aakash Verma

Reputation: 3994

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');
    ...

Upvotes: 1

Related Questions