UNPKG

argum

Version:

A package for getting command line arguments in a simple way.

85 lines (79 loc) 2.52 kB
/** * Given a prefix of a parameter it returns the value of that parameter. * Note that the prefix and parameter need to be separated by '=' sign * in order for this function to work. * * @param prefix {string} the prefix with which the parameter starts * @param required whether or not that parameter is required * @param defaultValue if required is set to false this the value that will be returned if the parameter is not passed to the process * @returns {*} */ exports.get = function (prefix, required, defaultValue) { var found = false; var value = defaultValue; // loop through all arguments passed to the process for (var i = 0; i < process.argv.length; i++) { if (process.argv[i].indexOf(prefix) == 0) { // parameter found found = true; if (process.argv[i].indexOf('=') == -1) { // equals sign not found throw new Error('Equals sign not found. Parameter\'s name and value are required to be separated by equals sign.'); } else { var start = process.argv[i].indexOf('=') + 1; var end = process.argv[i].length; value = process.argv[i].slice(start, end); // get the value of the parameter break; } } } // if required but not found print an error message // out and terminate the process if (required && !found) { throw new Error('Required paramater ' + prefix + ' not passed in.'); } return value; }; /** * Searches for argument in object if found returns the value * if not found it either raises an error or returns the specified * return value * * @param object the object to search in * @param argument the argument to search for * @param required if the argument is required * @param defaultValue the default value in case the argument is not required and not found * @returns {*} */ exports.object = function(object, argument, required, defaultValue) { if (typeof object !== 'object') { throw new Error('First argument is not an object.'); } if (argument in object) { return object[argument]; } else { if (required) { throw new Error('Required parameter missing: ' + argument); } else if (defaultValue) { return defaultValue; } else { return false; } } }