Loading and reading a CSV-Parse file
I am trying to read a csv file with multiple same columns using Node CSV-Parser
'from' ' 'to' 'from' ' 'to' 'from' ' 'to'
'Germ' ' 'NL' 'Turk' ' 'US' 'Nile' ' 'BR'
'Germ' ' 'NL' 'Turk' ' 'US' 'Nile' ' 'BR'
'Germ' ' 'NL' 'Turk' ' 'US' 'Nile' ' 'BR'
'Germ' ' 'NL' 'Turk' ' 'US' 'Nile' ' 'BR'
And below is my code:
req.file('ratefile').upload(function (err, uploadedFile) {
if (err) return ResponseService.json(500, err, 'Uploaded Failed');
console.log(uploadedFile.length) //
if (uploadedFile.length) {
rs = fs.createReadStream(uploadedFile[0].fd);
parser = parse({columns: true, trim: true}, function (err, data){
var record = {};
console.log(data);
_.forEach(data, function(datum, index){
var routeName = datum['from'] +"-"+ datum['to'];
console.log(routeName);
record.name = datum['from'] +"-"+ datum['to'];
record.to = datum['to'];
record.from = datum['from'];
});
return ResponseService.json(200, res, 'file successfully uploaded');
});
rs.pipe(parser);
} else {
return ResponseService.json(500, res, 'Please upload a file')
}
});
And when I run this, it is only the last column in the csv file.
'from' ' 'to'
'Nile' ' 'BR'
'Nile' ' 'BR'
'Nile' ' 'BR'
Any help would be greatly appreciated. Thanks to
source to share
It will sort out something like
{
"from": "Germ",
"to" : "NL",
"from": "Turk",
"to" : "US",
...
}
And of course this is not true JSON, look at the duplicate keys. Thus, the last pair of key values effectively overrides the previous pair.
In your line
parser = parse({columns: true, trim: true}, function (err, data){
Use a function or null
as a value columns
like
parse({columns: null, trim: true}
And print your result and then change your own needs. It can use as well function
, but I'm not sure what function
can solve your problems as it will parse your only csv line in a single one anyway object
.
source to share