Mr Long
Mr Long

Reputation: 3

Global variable in javascript function

This is my code:

var csv = require('csv');

var Loader = function() {
  var rows;
  csv()
  .from.path('./data/ebay.csv', {
    columns: true,
    delimiter: ';'
  })
  .to.array( function(rows) {
    setRows(rows);
  });
  function setRows(input) {
    rows = input;
  }
  return rows;
};

module.exports = Loader;

I want to get rows when I call Loader object. I'am beginner in OOP Javascript, so I have no idea what to do it. Where do I start learning javascript oop with node? I found many tutorials that describe how to start with node and how to make webs using various frameworks, but this I already know. I programmed in PHP and now moving to NodeJS and I'm wasted.

Upvotes: 0

Views: 126

Answers (1)

phihag
phihag

Reputation: 288240

Like all node.js functions that deal with I/O csv works asynchronously. Therefore, the call csv.from..to.. returns immediately, but the callback function is only called later. Make your Loader asynchronous as well, like this:

var csv = require('csv');
var Loader = function(onData) {
  csv()
  .from.path('./data/ebay.csv', {
    columns: true,
    delimiter: ';'
  })
  .to.array(onData);
};
module.exports = Loader;

Upvotes: 1

Related Questions