Nodejs and TypeError method 'trim' undefined when processing data from streaming


i have data below from streaming:


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.connect(PORT, HOST, function () {
    console.log('Connected to: %s : %d', HOST, PORT);

client.on('close', function (hadError) {

client.on('error', function (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);

            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.

Problem courtesy of: hbinduni


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.

Solution courtesy of: Jani Hartikainen


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.