【问题标题】:Inputs needed to create command line utility using nodejs使用 nodejs 创建命令行实用程序所需的输入
【发布时间】:2019-04-02 12:02:26
【问题描述】:

我们正在尝试使用 node.js 创建一个命令行实用程序。 我们需要创建类似geth 的实用程序,例如用户将使用一个命令启动该实用程序,这将打开它自己的终端,我们可以在其中执行子命令。 我们需要创建自己的嵌套终端的原因是我们需要在一个命令中初始化几个变量,并且应该能够在第二个中检索它们等等......

所以我们有一些问题: 1) node.js 适合这个吗? ,我们尝试使用commander,但它创建命令,不维护会话' 2)我们尝试了inquirer + commander + node-cmd,但它也给出了问题。

也许我们这里的方法是错误的,有人可以指导我们解决这个问题吗?非常感谢这方面的任何投入。

【问题讨论】:

  • 这个问题对于 StackOverflow 来说可能过于宽泛。你能把你的问题提炼得更具体吗?

标签: javascript node.js shell command-line command


【解决方案1】:

您从错误的角度解决了问题。 commandernode-cmd 允许您在节点程序中运行 shell 命令。你需要的是实际实现一个shell。

您的起点应该是readline 模块,它允许您处理stdin 数据。这个简单的例子展示了如何创建一个处理 2 个命令的 shell:helloexit

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('> ', (answer) => {
  if (answer == "hello") {
    console.log("world");
  }

  if (answer == "exit") {
    rl.close();
  }
});

【讨论】:

  • 感谢您的回复,我们认为这是我们的第二个选择。这是所有命令行的创建方式吗???
  • 如果您想使用 node,这只是一个起点,但还有其他技术可用于构建命令行工具
【解决方案2】:

“node.js 适合这个吗?”
当然,为什么不呢?你可以用 Node.js 做任何你想做的事情

显然您可以从头开始创建它,但是有一些很好的库可以帮助您完成这项任务。您已经尝试了其中的一些。

个人,我会尝试Vorpal制作一个cli应用:

const vorpal = require('vorpal')();

let variables = {};

vorpal
  .command('init', 'Initialise few variables.')
  .action(function() {
    return this.prompt({
      name: 'etherum_password',
      message: 'Please enter your etherum wallet password: '
    }, (result) => {
      variables = result
    })
  });

vorpal
  .command('pswd', 'Show etherum wallet password.')
  .action(function() {
    if (variables.etherum_password)
      this.log(variables.etherum_password)
    else this.log('Please run \'init\' command before.');
  });

vorpal
  .delimiter('$')
  .show();

注意prompt 方法直接受到Inquirer.js

的启发

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多