1

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.

4
  • 1
    Right click -> View Source. Commented Mar 29, 2014 at 22:52
  • @h2ooooooo ive tried and no i cant read it. Commented Mar 29, 2014 at 22:53
  • Get better at reading code :); Commented Mar 29, 2014 at 22:54
  • @RPM how am i automatically supposed to know what this means. imgur.com/wqrcxCP Commented Mar 29, 2014 at 22:58

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.