Get argument from command line - Node.js Environment

Node.js examples for Environment:OS

Description

Get argument from command line

Demo Code

/***********************************************************
 * Author: @mervinej//from   www  .  jav  a  2s. com
 * Licence: MIT
 * Date: 11/27/2013
 *
 * Shared utils for phantomjs-tools
 *
 ***********************************************************/
var fs = require('fs');

// automatically shared to anything that requires this file.
console.dir = function dir(obj) {
    console.log(JSON.stringify(obj, null, 2));
};

Array.prototype.copyArgs = function copyArgs() {
    var n = new Array();
    this.forEach(function(e) {
        n.push(e);
    });
    n.shift(); // remove file name
    return n;
};

// usage:
//
// var arg = system.args.copy(); // see above
// var useFULL = arg.getArgs(['--full', '-f'], false); // false
// var useJSON = arg.getArgs(['--json', '-j'], false); // true
// var gotNAME = arg.getArgs(['--name', '-n'], true);  // foo
Array.prototype.getArg = function getArg(flags, hasValue) {
    for (var i = 0; i < flags.length; i++) {
        var pos = this.indexOf(flags[i]);
        if (pos !== -1) {
            if (hasValue) {
                try {
                    var ret = this[pos+1];
                    console.log('ret: ' + ret);
                    this.splice(pos,2);
                    return ret;
                } catch (e) {
                    console.trace(e);
                    return false;
                }
            }
            var len = this.length-1;
            this.splice(pos, 1);
            return true;
        }
    }
    return false;
};

function trim(str) {
    return str.replace(/^\s+/,'').replace(/\s+$/,'');
}

Related Tutorials