I am trying to read a csv file using node js. Her is my code
fs.readFile(config.csvUploadPath, function read(err, data) {
if (err) {
throw err;
}
console.log(data + 'my data')
});
CONSOLE:
ID
D11
D33
D55
Here I want to get the elements in the column ID and store those in an array. How can I do that? Can anyone suggest me help. Thanks. My controller:
var partnersModel = new partners(params);
fs.readFile(config.csvUploadPath, function read(err, data) {
if (err) {
throw err;
}
dataArray = data.toString().split(/\r?\n/);
dataArray.forEach(function(v,i){
if(v !== 'DUI'){
partnersModel.dui.push(v);
}
});
});
partnersModel.save(function(error, response){
Use a library, CSV has lots of gotchas. I have come to enjoy the package
csv
. It is located here: https://www.npmjs.com/package/csv . Here is a very quick example using the async api.Since your file does not have multiple values per row and contains no delimiters besides newline, it is only trivially CSV. Maybe
String.prototype.split()
is for you?From How to read data From *.CSV file using javascript?, use the jQuery-CSV library.
code snippet from
jquery-csv
's examples here.