cscheid / rserve-js

Javascript implementation of the Rserve protocol
MIT License
47 stars 32 forks source link

Minor issue when deploying in an Express app #17

Closed pbruneau closed 10 years ago

pbruneau commented 10 years ago

After successfully running the quick tour, I went on using rserve-js in the context of an express app.

I used the following snippet:

var r = require('rserve');
r = r.create();

However, if I put console.log(r.running) immediately after, I get "false": I tentatively explain this by assuming the R client is actually running as the result from an asynchronous call.

This becomes a (minor) problem when I want to init an R session prior to REST call route definition: having r.running to false causes (logically) r.eval to crash.

I circumvented with the following snippet:

(function init() {
  if(r.running) {
    r.eval('setwd(".."); source("initScript.R")', function() {
      console.log("Initialized.");
    });
  } else {
    setTimeout(init, 100);
  }
})();

But maybe there's a more elegant solution? I didn't notice a callback argument to r.create(), but I may have missed something?

Other minor point: the version installable via npm (https://www.npmjs.org/package/rserve) crashes. The crash is caused by the following snippet, present in the git version, and missing in the npm version:

opts = _.defaults(opts || {}, {
    host: 'http://127.0.0.1:8081',
    on_connect: function() {}
});

Using the git version in place of the npm version fixes the issue.

cscheid commented 10 years ago

(I hope you don't mind the minor edits I made to your post)

Thanks for the report about NPM! I'll update it next chance I get (which will be in about 2 weeks).

The callback argument to r.create() is on_connect, used like this. Does that solve your problem?

In passing, what's an Express app? (That should tell you how little I actually know about the node ecosystem)

ghost commented 10 years ago

OK! I didn't pay enough attention to the opts object, but now I see, thanks!

Express is a node module with many utilities to support the creation of REST API's - in brief, provide access to data resources through a standardized URL nomenclature.

An example taken from my app, where a route is defined in conjunction to using rserve:

app.get('/data/:dataId', function(req, res) {
    r.eval("dim("+req.params.dataId+")", function(err, ans) {
        if(ans === undefined) {
            res.statusCode = 404;
            res.send("data not found");
        } else {
            res.json(makeArray(ans.value.value).map(function(d) {
                return {
                    value: d
                };
            }));
        }
    });
});

The route handles HTTP requests following the specified template, gets the dimensions of the associated R object using Rserve, and returns a JSON object.

cscheid commented 10 years ago

Ah, Flask for Node!. Very nice :) Thanks!