title: call shell script from node.js
body: <p>How can I generate a script in Node.js and pipe to the shell?</p>
  
  <p>E.g. I can create this file, e.g. <code>hello.R</code>, make it executable <code>chmod +x hello.R</code> and run it from the command line, <code>./hello.R</code>:</p>
  
  <pre><code>#!/usr/bin/Rscript
  hello &lt;- function( name ) { return (sprintf( "Hello, %s", name ); })
  cat(hello("World"));
  </code></pre>
  
  <p>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 <code>exec</code> or <code>spawn</code>?), and read <code>stdout</code>.  </p>
  
  <p>But I can't quite figure out how to pipe a script to R.  I tried this (among other things):</p>
  
  <pre><code>var rscript = [       
      hello &lt;- 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);
  }); 
  </code></pre>
  
  <p>However, this fails as it seems neither <code>/usr/bin/R</code> nor <code>/usr/bin/Rscript</code> understand the <code>-c</code> switch:</p>