Commander.js: Support piping

Created on 18 Mar 2013  路  3Comments  路  Source: tj/commander.js

Say you want to support piping in your script, e.g.:

echo "foo bar" | ./test.js

That鈥檚 currently possible using code that looks like this:

var data = '';
function withPipe(data) {
   console.log('content was piped');
   console.log(data.trim());
}
function withoutPipe() {
   console.log('no content was piped');
}

var self = process.stdin;
self.on('readable', function() {
    var chunk = this.read();
    if (chunk === null) {
        withoutPipe();
    } else {
       data += chunk;
    }
});
self.on('end', function() {
   withPipe(data);
});

It would be neat if commander.js could somehow abstract all this away and make it easier to write scripts that accept piped content.

enhancement

Most helpful comment

:+1:

This is what I did:

//...
var stdin = '';

program
  .command('some-command [message]')
  .action(function(message) {
    if(stdin) {
      message = stdin;
    }
  });

if(process.stdin.isTTY) {
  program.parse(process.argv);
}
else {
  process.stdin.on('readable', function() {
      var chunk = this.read();
      if (chunk !== null) {
         stdin += chunk;
      }
  });
  process.stdin.on('end', function() {
    program.parse(process.argv); 
  });
}

All 3 comments

:+1:

This is what I did:

//...
var stdin = '';

program
  .command('some-command [message]')
  .action(function(message) {
    if(stdin) {
      message = stdin;
    }
  });

if(process.stdin.isTTY) {
  program.parse(process.argv);
}
else {
  process.stdin.on('readable', function() {
      var chunk = this.read();
      if (chunk !== null) {
         stdin += chunk;
      }
  });
  process.stdin.on('end', function() {
    program.parse(process.argv); 
  });
}

I did the same thing here. Works like a charm.

Popular approach from @jrschumacher , thanks

This issue has not had any activity in over six months. It isn't likely to get acted on due to this report.

Feel free to open a new issue if it comes up again, with new information and renewed interest.

Thank you for your contributions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mtrabelsi picture mtrabelsi  路  3Comments

hossamelmansy picture hossamelmansy  路  4Comments

akki005 picture akki005  路  5Comments

shadowspawn picture shadowspawn  路  4Comments

DeoLeung picture DeoLeung  路  4Comments