【问题标题】:How to get multiple input lines in cli script如何在 cli 脚本中获取多个输入行
【发布时间】:2021-05-15 14:53:56
【问题描述】:

我有这个简单的节点 cli 脚本。

#!/usr/bin/env node

const inquirer = require('inquirer');
const axios = require('axios');

( async () => {
    const lang = await inquirer.prompt([
        {
            type: 'list',
            name: 'to',
            message: 'Select translation language:',
            choices: ['it','en','es','fr','de','pt']
        }
    ]);

    const input = await inquirer.prompt([
        {
            type: 'input',
            name: 'from',
            message: 'Text to translate:'
        }
    ]);

    console.log(lang, input);

    const translation = await axios({
        method: 'GET',
        url: 'https://translate.googleapis.com/translate_a/single',
        params: {
            client: 'gtx',
            sl: 'auto',
            tl: lang.to,
            dt: 't',
            q: input.from
        }
    });

    console.log(translation.data);
})();

我想创建一个简单的 cli 翻译工具,但我的用户输入有问题。由于程序将在 cli 中运行,我需要一种方法让用户能够输入可翻译的多行输入文本。我已经使用查询器进行了测试,但使用 editor 类型作为提示将打开一个 vim 实例,对于没有经验的用户来说,这不是最佳选择。有没有办法让用户能够键入多行输入来处理?

【问题讨论】:

  • 尝试使用 readline,它让您可以选择使用 line 模式进行 CLI 输入
  • 你能提供一个例子吗?我在过去的readline中使用过,但从未用于多行输入

标签: javascript node.js


【解决方案1】:

尝试使用 readline-

var readline = require('readline');

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

rdLine.prompt();

rdLine.on('line', function (line) {
    console.log(line)
});

【讨论】:

  • 但是如果用户需要在按下回车时插入换行符,这将处理输入或者我错了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 2014-06-24
  • 2016-03-06
  • 2020-03-09
  • 1970-01-01
相关资源
最近更新 更多