Question

How would i go about creating a CLI like interface in JavaScript?

What i mean is an example like this cmd.fm

I work with a lot of jquery and forgive me if i'm wrong but the only idea i have as to how to build this is by getting what the user typed in and using the switch function and checking if the command exists and then executing the command.

Was it helpful?

Solution

It all depends how complicated you need the commands to be!

I'll assume you you know how to render the page in lines, and capture keypresses (simplest way would be to style a text input, and listen for the return key, rather than trying to decode a key event).

I'd build a data structure like this (in JS):

var commands = {
    "doThing": function(args) { /* do stuff with the args */ },
    "doAnotherThing": function(args) { /* do other stuff with the args */ }
}

The user would type:

> doThing foo bar blah

In this simple example, you'd split the line by space characters, and treat the first element in the resulting array as your command name. You'd then check to see if commands[commandName] exists, and if so, run it: commands[commandName](args);

If you want to do something more advanced, you're going to need to write a tokeniser (technically the split on space is a simple tokeniser) - then things get more complicated, but the same basic method applies.

I hope that's enough to get you started.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top