Last active
August 29, 2015 14:04
-
-
Save drFabio/5ede2a70471218c03c88 to your computer and use it in GitHub Desktop.
CSV Reader in nodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs=require('fs'); | |
var lazy = require("lazy") | |
function CSVReader(linesToSkip,separator,convertKeyFunction){ | |
if(!linesToSkip){ | |
linesToSkip=0; | |
} | |
if(!separator){ | |
separator=';'; | |
} | |
this._linesToSkip=linesToSkip; | |
this._separator=separator; | |
this._convertKeyFunction=convertKeyFunction; | |
} | |
CSVReader.prototype.readFile=function(fileName){ | |
var self=this; | |
var count=0; | |
var keys; | |
var data; | |
var lines=[]; | |
var ret=[]; | |
var length; | |
fs.readFileSync(fileName).toString().split('\n').forEach(function(line){ | |
if(line){ | |
line=line.replace('\r',''); | |
data=line.split(self._separator); | |
if(count==self._linesToSkip){ | |
//é um header | |
keys=data; | |
length=data.length; | |
if(self._convertKeyFunction){ | |
for(var i=0;i<length;i++){ | |
keys[i]=self._convertKeyFunction(keys[i]); | |
} | |
} | |
} | |
else if(count>self._linesToSkip){ | |
var obj={}; | |
for(var i=0;i<length;i++){ | |
obj[keys[i].toString()]=data[i]; | |
} | |
ret.push(obj); | |
} | |
count++; | |
} | |
}); | |
return ret; | |
} | |
module.exports=CSVReader; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment