execSync icon indicating copy to clipboard operation
execSync copied to clipboard

writing to stdin?

Open rodw opened this issue 12 years ago • 1 comments

My apologies if I'm missing something obvious, but I've poked around in the code and the issue list and it isn't clear to me if or how to do this.

Is there a way to provide data for the input stream being read by the process invoked by execSync.run or execSync.exec? I.e., can I provide a buffer or string, or write to the stream directly?

(A somewhat laborious work-around would be for me to write to a temp file and then cat that file as part of the command passed to exec or run, but I wonder if that is built in or could be added.)

rodw avatar Oct 20 '13 21:10 rodw

For what it's worth, since I needed it anyway I put together a quick-and-dirty version of the work-around described above. Here's a sanitized JS version (my original is factored differently and implemented in CoffeeScript, but this one seems to work.)

This isn't particularly robust (it doesn't handle errors, and may not handle binary data or work on Windows properly), but might save anyone reading this thread in the future a little bit of time.

var fs = require('fs');
var ExecSync = require('execSync');
var temp = require('temp');
var is_windows = require('os').platform().indexOf('win') === 0

function exec_with_stdin(data,cmd) {
  // write the given `data` to a temp file
  var temp_file = temp.path({suffix: '.temp-data'});
  fs.writeFileSync(temp_file,data);

  // prepend `cat <data> |` to the given command
  if(is_windows) {
    cmd = "type " + temp_file + " | " + cmd;
  } else {
    cmd = "cat " + temp_file + " | " + cmd;
  }

  // execute the modified command
  var result = ExecSync.exec(cmd);

  // remove the temp file
  fs.unlink(temp_file);

  // return the result from executing the command
  return result;
}

// Example of use:
var data = "This is a test.\nLorem ipsum dolor sit amet, consectetuer adipiscing elit.\n";
var cmd = "wc";
var result = exec_with_stdin(data,cmd);
console.log(result);  // yields: { code: 0, stdout: '      2      12      74\n' }

// (Check /tmp before and after running to validate the temporary file wasn't left behind.)

rodw avatar Oct 20 '13 22:10 rodw