Learner85
Learner85

Reputation: 51

Javascript code returning undefined:Nan in the execution output?

I am a newbie to javascript and trying to learn some basics. So I wrote a small script for file reading. Below is my code.

// Load the fs (filesystem) module
var fs=require('fs');

// Read the contents of the file into memory.
fs.readFile('example.txt', function (err, logData) {
  // If an error occurred, throwing it will
    //display the exception and end our app.
  if(err) throw err;
  // logData is a Buffer, convert to string.
  var text = logData.toString();

  var results = {};
  var lines = text.split('\n');
  lines.forEach(function(line){
    var parts = line.split(' ');
    var letter = parts[1];
    var count = parseInt(parts[2]);

    if (!results[letter]){
      results[letter] = 0;
    }
    results[letter] +=parseInt(count);
    });
  console.log(results);
}); 

my input file is

2013-08-09T13:50:33.166Z A 2
2013-08-09T13:51:33.166Z B 1
2013-08-09T13:52:33.166Z C 6
2013-08-09T13:53:33.166Z B 8
2013-08-09T13:54:33.166Z B 5

Number of lines in example.txt is 5

wc -l example.txt 
5 example.txt

Executing the above code using Node.js results in

node my_parser.js 
[ '2013-08-09T13:50:33.166Z A 2',
  '2013-08-09T13:51:33.166Z B 1',
  '2013-08-09T13:52:33.166Z C 6',
  '2013-08-09T13:53:33.166Z B 8',
  '2013-08-09T13:54:33.166Z B 5',
  '' ]
{ A: 2, B: 14, C: 6, undefined: NaN }

When there are only five lines in the example.txt file? Why is an extra empty string added to the list? Is this expected from split function? Please help

Upvotes: 1

Views: 570

Answers (1)

danwellman
danwellman

Reputation: 9273

Does the file have a new-line character at the end? If so the last array item will be an empty string

Upvotes: 4

Related Questions