David Je David Je - 6 months ago 24
Node.js Question

Reading csv data to array and perform operation

I am trying to operate on csv data. [this is the csv file][1]

[1]: http://pastebin.com/MzLmQtye. I have to get the subtracted result of MxT and MnT.

var fs = require('fs'),
fileName = "weather.csv",
bufferString;
var arr = new Array();


fs.readFile(fileName, "utf8", function(err, data) {
if(err){
console.log(err);
return;
}
bufferString = data.toString();
arr = bufferString.split('\n');
//arr = arr.split(',');
console.log(arr[1][1]);
});


From the above code, I get comma as well on array data. The
split(,)
also gives
TypeError: arr.split is not a function
error. How to do this.

I think best idea for me is to create object like this:

1:{
max:""
min:""
}
2:{
max:""
min:""
}


This would make it easy to do the subtraction operation. How to do this? I got puzzled. Please mention if I am not clear.

Answer

Iterate over each line and split with comma. So following logs all MxT and MnT values to console:

fs.readFile(fileName, "utf8", function(err, data) {
    if(err){
        console.log(err);
        return;
    }
    bufferString = data.toString();
    arr = bufferString.split('\n');
    var line;
    for(var i=0; i < arr.length; i++){
          line = arr[i].split(',');
          console.log(line[1]); // MxT
          console.log(line[2]); // MnT
    }
 });