0

Sorry if the issue is not particularly clear (I am still a novice). I have a simple setup to get data from a mock feed and then convert the data to JSON. I can retrieve the data and display it but converting it to JSON has proved a bit tricky.

var completeData = '';
let client = net.createConnection({ port: 8282 }, () => {

client.write('Test Worked!\r\n');
});


client.on('data', (data) => {
// change buffer to string
let readData = data.toString();

// Merge response data as one string
completeData += readData += '\n';

// End client after server's final response
client.end();
});

This is the sample output for one packet below (Pipe delimited with some data escaped):

|2054|create|event|1497359166352|ee4d2439-e1c5-4cb7-98ad-9879b2fd84c2|Football|Sky Bet League Two|\|Accrington\| vs \|Cambridge\||1497359216693|0|1|

I would like the pipes to represent keys/values in an object. The issue is that some of the values are escaped (e.g '\|' ). That kind of makes using the split function in Javascript difficult.

My question is there a way to get pipe delimited data from TCP packets and then convert them to a JSON object?

Any help will be highly appreciated. Thank you.

Tesla
  • 63
  • 1
  • 1
  • 6
  • Please see the [How to create a minimal, complete and verifiable example](https://stackoverflow.com/help/mcve) help page. Asking readers to reverse engineer the proprietary syntax used in the data feed from non working code is like leaving out what the code is supposed to do. – traktor Dec 06 '17 at 00:01
  • Made the question a bit simpler, Hopefully I get and answer this time. Not sure what the issue is. – Tesla Dec 08 '17 at 10:34

1 Answers1

0
const { StringDecoder } = require("string_decoder");
let header = "";
const decoder = new StringDecoder("utf8");
let str = decoder.write(chunk); // chunk is your data stream
header += str;
header.replace(/s/, "");
var obj = JSON.parse(header);
console.log(obj);

While receiving data through tcp ip net npm package, we face trouble in parsing the continous stream of data. string_decoder is a npm package which can parse it into a json readable format. Also since the packets being received has a variable length so one can basically put a check on header.length to fetch only a complete set of object.

Amit
  • 1
  • 2
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 19 '22 at 08:06
  • updated with detailed information on how the above code works – Amit Sep 03 '22 at 10:56