@wbg-mde/r-script
Version:
A simple little module for passing data from NodeJS to R (and back again). Panapps customized version of r-script package for WBG-metadata-editor.
79 lines (70 loc) • 2.28 kB
JavaScript
var _ = require("underscore"),
child_process = require("child_process");
function init(path) {
var obj = new R(path);
return _.bindAll(obj, "data", "call", "callSync", "start");
}
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);
child.on('error', function(err) {
callback(err, null);
});
child.stderr.on("data", callback);
child.stdout.on("data", function(d) {
// handle json parse error
var returnValue = 0;
try {
returnValue = JSON.parse(d);
} catch (e) {
}
callback(null, returnValue);
});
};
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));
};
R.prototype.start = 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);
child.on('error', function(err) {
callback(err, null, null);
});
child.stderr.on("data", function(err, data){
callback(err, data, child.pid);
});
child.stdout.on("data", function(d) {
// handle json parse error
var returnValue = 0;
try {
returnValue = JSON.parse(d);
} catch (e) {
}
callback(null, returnValue, child.pid);
});
};
module.exports = init;