Skip to content

Instantly share code, notes, and snippets.

@FrancoAra FrancoAra/bin\app
Created Apr 24, 2012

Embed
What would you like to do?
Handles commands, options and parameters to call a nodejs app
#!/usr/bin/env node
// This file has to have execution permission.
// You can do it with 'sudo chmod 777 thisfile', will give write, read and execute permissions to everyone.
// To execute it from terminal be sure that your $PATH is updated, adding the path of this file to it.
var delegate = require('../lib/delegate') // Replace delegate with the module which will handle the commands functionality.
var args = new ArgumentsCollection();
// # Declaration of your app arguments
// # ##################################
args.add('name_of_argument', delegate.your_app_handler_function, 'Argument description');
args.add('help', args.help, 'Lists all commands.'); // args.help is a built-in function that lists all the commands with its description.
args.add('start', delegate.initServer, 'Starts the server.');
args.add(null, delegate.main, '') // Supports no command.
args.execute();
// # Class
// # ##################################
function ArgumentsCollection () {
var collection = [];
var options = [];
var params = [];
var command = null;
this.add = function (n, c, d) {
collection.push({name: n, callback: c, description: d});
};
this.execute = function () {
if (process.argv.length == 2) {
for (var key in collection) {
if (collection[key].name == null) {
command = collection[key];
break;
}
}
}
for (var key = 2; key < process.argv.length; key++)
iteration(process.argv[key]);
if (command != null)
command.callback(options, params);
else
console.log('No such command, use \'help\' for a list of usefull commands.');
};
this.help = function () {
for (var key in collection) {
console.log(collection[key].name + '\t\t' + collection[key].description);
}
};
function iteration (arg) {
if (command == null) {
for (var key in collection) {
if (collection[key].name == arg) {
command = collection[key];
break;
}
}
}
else if (arg.match(/^-/))
options.push(arg);
else
params.push(arg);
};
};
// This file is your application delegate
exports.main = function () {
console.log('Starting your application...');
}
exports.initServer = function (options, params) {
console.log(options);
console.log(params);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.