Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to alter a global variable from a function called when an event triggers?

How to alter a global variable from a function called when an event triggers?

Problem

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?

Problem courtesy of: user1700840

Solution

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);
}
Solution courtesy of: Sherlock

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to alter a global variable from a function called when an event triggers?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×