2

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:

1

1 Answer 1

2

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 */
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It turns out the issue is R and Rscript don't read from stdin by default, and the workarounds (stackoverflow.com/questions/9370609/piping-stdin-to-r) don't play well with spawn. Will noodle on that, for now am writing the code as a file to be read in by R.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.