Tom Cardoso
Tom Cardoso

Reputation: 99

Meteor.js: Parsing CSV on the server and passing back to client with node-csv-string

I'm working on a project that involves parsing a CSV-like file where the delimiter is determined on parse.

I've been using PapaParse, but unfortunately the delimiter checking doesn't seem robust enough, so I'm using https://github.com/touv/node-csv-string instead. So far so good.

I've installed meteorhacks:npm and meteorhacks:async but I'm uncertain how to pass the parsing request back and forth between the server and the client. I understand that I need to be doing this with callbacks since it's async, just not sure how to go about it.

On my client side, this is what I have:

var parsedData = Meteor.call("parseCSV", data);

On the server, I'm using a method something like:

Meteor.methods({
  parseCSV: function (data) {
    var CSV = Meteor.npmRequire('csv-string');
    return CSV.parse(data);
  }
});

Though that clearly won't cut it because of the async requirements. I tried something like

var response = Async.runSync(function(done) {
  CSV.parse((data), function(err, data) {
    done(null, data);
    console.log(data)
  });
});

But honestly it was a stab in the dark, and it hasn't worked. I need to be able to access the parsed CSV through parsedData in the client. Any help would be greatly appreciated!

Upvotes: 1

Views: 597

Answers (1)

rgoomar
rgoomar

Reputation: 184

You could use Meteor's Meteor.wrapAsync method.

Meteor.methods({
  parseCSV: function (data) {
    var CSV = Meteor.npmRequire('csv-string');
    var parse = Meteor.wrapAsync(CSV.parse);
    return parse(data);
  }
});

The reason this occurs is because Meteor is using node Fibers and requires you to have synchronous code. You could also implement a fiber / future and send the output within the callback, but that is a more complicated solution and may not be needed.

Upvotes: 0

Related Questions