Skip to content

Instantly share code, notes, and snippets.

@nic-hartley
Created May 3, 2017 05:17
Show Gist options
  • Save nic-hartley/d8a001e3b71e0b48a21a5fc846ff8dbc to your computer and use it in GitHub Desktop.
Save nic-hartley/d8a001e3b71e0b48a21a5fc846ff8dbc to your computer and use it in GitHub Desktop.
A NodeJS mini-module-thing that allows fairly simple handling of command-line commands for your server
((initialCommands, undefined) => {
const readline = require('readline');
let commands = typeof initialCommands !== 'object' ? {} : initialCommands;
function replaceCommand(name, func) {
commands[name] = [func];
}
function addCommand(name, func) {
if (commands.hasOwnProperty(name)) {
commands[name].append(func);
} else {
commands[name] = [ func ];
}
}
function addAllCommands(kvps) {
for (var prop in kvps) {
if (kvps.hasOwnProperty(prop)) {
addCommand(prop, kvps[prop]);
}
}
}
function removeCommand(name, func = undefined) {
if (typeof func === 'undefined') {
delete commands[name];
} else {
let list = commands[name];
let rmIdx = list.indexOf(func);
if (rmIdx >= 0) list.splice(rmIdx, 1);
}
}
module.exports = {
replaceCommand,
addCommand,
addAllCommands,
removeCommand
};
const stdin = readline.createInterface({
input: process.stdin,
output: process.stdout
});
stdin.on('line', (line) => {
var args = line.trim().split(' ', 2);
if (args[0] === 'help' || args[0] === '?') {
console.log('The following commands are available:');
console.log('- help (or ?)');
for (var prop in commands) {
if (commands.hasOwnProperty(prop)) {
console.log('- %s', prop);
}
}
} else if (commands.hasOwnProperty(args[0])) {
commands[args[0]].forEach(e => e(args[1]));
} else {
console.log("Invalid command. Type `help` to get a list of commands.");
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment