prototype
prototype

Reputation: 7970

call shell script from node.js

How can I generate a script in Node.js and pipe to the shell?

E.g. I can create this file, e.g. hello.R, make it executable chmod +x hello.R and run it from the command line, ./hello.R:

#!/usr/bin/Rscript
hello <- function( name ) { return (sprintf( "Hello, %s", name ); })
cat(hello("World"));

What I'd like to do is to do the equivalent from Node. Specifically generate a more complex R script in memory (e.g. as a string using templating, etc.), execute it (using exec or spawn?), and read stdout.

But I can't quite figure out how to pipe a script to R. I tried this (among other things):

var rscript = [       
    hello <- function( name ) { return (sprintf( "Hello, %s", name ); })
    cat(hello("World"));
].join('\n');

var exec = require('child_process').exec;
exec(rscript, { shell: '/usr/bin/R'}, function(err, stdout, stderr) {
   if (err) throw(err);
   console.log(stdout);
}); 

However, this fails as it seems neither /usr/bin/R nor /usr/bin/Rscript understand the -c switch:

Upvotes: 2

Views: 1875

Answers (1)

ikrabbe
ikrabbe

Reputation: 1929

Check the nodejs docs of child_process. You should be able to spawn an Rscript or R command just as you would do on the terminal, and send your commands over child.stdin.

var c = require('child_process');
var r = c.spawn("R","");
r.stdin.write(rscript);
/* now you should be able to read the results from r.stdout a/o r.stderr */

Upvotes: 2

Related Questions