Reputation: 451
Using NodeJS and node-csv, I'm trying to load rows in a Array. From an example in the module:
// node samples/string.js
csv()
.from.string(
'#Welcome\n"1","2","3","4"\n"a","b","c","d"', {
comment: '#'
})
.to.array(function (data) {
console.log(data)
});
// [ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ]
But if inside function (data) I try to add each row to an Array defined in the global scope, it doesn't alter it. It's obvious I don't understand JS variables scope, but what's the best pattern to solve this problem?
Upvotes: 0
Views: 55
Reputation: 5627
It looks like it is altering the rows variable, but the console.log() call is being called before the rows are pushed. You can use the .on('end') event to call a function after they have been pushed.
var csv = require('csv');
var rows = new Array();
csv()
.from.string(
'#Welcome\n"1","2","3","4"\n"a","b","c","d"', {
comment: '#'
})
.to.array(function (data) {
rows.push(data);
console.log(rows);
}).on('end', function() {
logRows();
});
var logRows = function() {
console.log(rows);
}
Upvotes: 1