bindiego
7/15/2015 - 6:39 AM

Node command line utility sample.

Node command line utility sample.

#!/usr/bin/env node

// returning code
/*
if (err) {
  process.exit(1);
} else {
  process.exit(0);
}
*/

// redirection, pipe
// echo 'wubin' | ./utils.js
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(data) {
  process.stdout.write(data);
});

// system signals
// kill -s SIGINT [process_id]
process.on('SIGINT', function(){
  console.log('Got a SIGINT');
  process.exit(0);
});
{
  "name": "main",
  "description": "node shell example",
  "bin": {
    "main": "main.js"
  },
  "dependencies": {
    "shelljs": "^0.5.1",
    "yargs": "^3.15.0"
  }
}
#!/usr/bin/env node

require('shelljs/global')

var argv = require('yargs')
  .command("morning", "good morning", function (yargs) {
    echo("Good Morning");
    var argv = yargs.reset()
      .option("m", {
        alias: "message",
        description: "provide any sentence"
      })
      .help("h")
      .alias("h", "help")
      .argv;
    echo(argv.m);
  })
  .command("evening", "good evening", function (yargs) {
    echo("Good Evening");
    var argv = yargs.reset()
      .option("m", {
        alias: "message",
        description: "provide any sentence"
      })
      .help("h")
      .alias("h", "help")
      .argv;
    echo(argv.m);
  })
  .argv;
#!/usr/bin/env node

// can directly use shell command in global mode
require('shelljs/global');

if (!which('git')) {
  echo("Sorry, this script requires git");
  exit(1);
}

mkdir('-p', 'out/Release');
cp('-R', 'stuff/*', 'out/Release');

cd('lib')
ls('*.js').forEach(function(file){
  sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
  sed('-i', /.*REMOVE_THIS_LINE.*\n/, '', file);
  sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, cat('macro.js'), file);
});
cd('..');

if (exec('git commit -am "Auto-commit"').code != 0) {
  echo("Error: Git commit failed");
  exit(1);
}
#!/usr/bin/env node

var shell = require('shelljs');
/*
var argv = require('yargs')
  .alias('n', 'name')
  .demand(['n'])
  .default({n: 'WB'})
  .describe({n: 'Your Name'})
  .argv;
*/

var argv = require('yargs')
  .option('n', {
    alias: 'name',
    demand: true,
    default: 'WB',
    describe: 'Your Name',
    type: 'string'
  })
  .usage('Usage: main [options]')
  .example('main -n wubin', 'say hello to wubin')
  .help('h')
  .alias('h', 'help')
  .epilog('copyright 2015')
  .argv;

/* test option is presented or not
var argv = require('yargs')
  .boolean(['y'])
  .argv;
*/
/*
var argv = require('yargs')
  .option('y', {
    boolean: true
  })
  .argv;
*/

shell.exec("echo Hello " + argv.n);
shell.exec("echo _: " + argv._); // raw parameters in an array ['A', 'B', 'C'], main.js A -n abc B C