forked from payousefi/r-script
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (44 loc) · 1.32 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var _ = require("underscore"),
child_process = require("child_process");
function init(path) {
var obj = new R(path);
return _.bindAll(obj, "data", "call", "callSync");
}
function R(path) {
this.d = {};
this.path = path;
this.options = {
env: _.extend({DIRNAME: __dirname}, process.env),
encoding: "utf8"
};
this.idCounter = 0;
this.args = ["--vanilla", __dirname + "/R/launch.R"];
}
R.prototype.data = function() {
for (var i = 0; i < arguments.length; i++) {
this.d[++this.idCounter] = arguments[i];
}
return this;
};
R.prototype.call = function(_opts, _callback) {
var callback = _callback || _opts;
var opts = _.isFunction(_opts) ? {} : _opts;
this.options.env.input = JSON.stringify([this.d, this.path, opts]);
var child = child_process.spawn("Rscript", this.args, this.options);
var body = "";
child.stderr.on("data", callback);
child.stdout.on("data", function(d) {
body += d;
});
child.on("close", function(code) {
callback(null, JSON.parse(body));
});
};
R.prototype.callSync = function(_opts) {
var opts = _opts || {};
this.options.env.input = JSON.stringify([this.d, this.path, opts]);
var child = child_process.spawnSync("Rscript", this.args, this.options);
if (child.stderr) throw child.stderr;
return(JSON.parse(child.stdout));
};
module.exports = init;