简体   繁体   English

我将如何在javascript中创建命令行界面?

[英]how would i go about creating a Command Line Interface in javascript?

How would i go about creating a CLI like interface in JavaScript? 我将如何在JavaScript中创建类似CLI的界面?

What i mean is an example like this cmd.fm 我的意思是这样的一个例子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. 我使用了大量的jQuery,如果我错了,请原谅我,但是关于如何构建它的唯一想法是通过获取用户键入的内容并使用switch函数并检查命令是否存在,然后执行命令。

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): 我将建立一个像这样的数据结构(在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); 然后,您需要检查commands[commandName]存在,如果存在,请运行它: 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. 我希望这足以让您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM