i have data below from streaming:
'ID|20120206|080500|0000001|0|1|record1|END'
'ID|20120206|080500|0000002|0|1|record2|END'
'ID|20120206|080500|0000003|0|1|record3|END'
and i want to process the streaming data line by line using nodejs code below:
var net = require('net');
var HOST = 'localhost',
PORT = 9010,
lastSeqNo = 0;
var client = new net.Socket();
client.setEncoding('ascii');
client.connect(PORT, HOST, function () {
console.log('Connected to: %s : %d', HOST, PORT);
});
client.on('close', function (hadError) {
console.log(hadError);
});
client.on('error', function (ex) {
console.log(ex);
});
var i = 1;
var Line = function (rows, data) {
this.SeqNo = parseFloat(rows[3].trim());
this.Date = rows[1].trim();
this.Time = rows[2].trim();
this.MsgType = parseInt(rows[4].trim(), 10);
this.Data = data;
};
client.on('data', function (data) {
var content = data.split('\r\n');
content.forEach(function (item) {
if (item.length > 0) {
console.log(i, item);
i++;
var rows = item.split('|'),
line = new Line(rows, data),
seqNo = line.SeqNo,
msgType = line.MsgType;
console.log('seqno:', seqNo);
}
});
});
after a few data line process, i got some error like below:
D:\test node\app.js:33
this.SeqNo = parseFloat(rows[3].trim());
^
TypeError: Cannot call method 'trim' of undefined
at new <anonymous> (D:\test node\app.js:33:37)
at D:\test node\app.js:48:24
at Array.forEach (native)
at Socket.<anonymous> (D:\test node\app.js:42:13)
at Socket.emit (events.js:67:17)
at TCP.onread (net.js:362:31)
could you help me what's wrong with my code above?
thank you. greeting from indonesia.
The data
event does not guarantee that it sends full lines at once. Most likely the problem is that you actually got less data than what your code expects, thus rows[3]
is undefined.
As you said yourself, you're streaming the data. When you listen for the data
event, you might be getting just small bits of your data at once - not the full batch at once.