extensa5620
extensa5620

Reputation: 699

Processing TCP data in javascript

I am receiving a chunk of data via TCP, in nodejs. I'm not good with the javascript and thought I should seek help.

Basically, I get a chunk of data ending in \r\n.

Data chunk
Door1,10:02:24\r\n
Door1,10:05:25\r\n
Door2,10:11:02\r\n
Door1,10:24:34\r\n
etc.

I am not sure how to process this. Initially i thought each data chunk consisted of only one line. That's when I did a

newData = data.split('\r\n');

But now the data chunk is coming in big chunks! How should i process the big chunk to break it into split-sized bits for my processing?

Upvotes: 0

Views: 119

Answers (1)

Mustafa
Mustafa

Reputation: 10413

If you want to process each line when you recieve them, you can use carrier module which will callback a function with the line recieved.

Its implementation is not rocket science, it just reads each chunk, and adds them to buffer until it finds a new line. Then it gets the content until the first new line and callbacks function. It keeps going until there is no new line in the previous data. Afterwards, you may have some data left, and it will be kept until a new chunk is recieved and it will go on like this.

Here is a quick implementation:

var net     = require('net'),
    carrier = require('carrier');

var server = net.createServer(function(conn) {
  var my_carrier = carrier.carry(conn);
  my_carrier.on('line',  function(line) {
    console.log('got one line: ' + line);
  });
});
server.listen(4001);

Upvotes: 2

Related Questions