【问题标题】:User Input Not Being Read Correctly in NodeJS CLI App在 NodeJS CLI 应用程序中未正确读取用户输入
【发布时间】:2019-07-04 00:59:04
【问题描述】:

我正在尝试从命令行收集用户输入以创建一个简单的命令行界面应用程序。我正在使用standard_input.on() 函数来捕获用户输入并使用它来确定用户应该在命令行中看到什么响应。回调函数中未正确读取正在捕获的数据。下面是代码。

const fs = require("fs"),
path = require("path");

const dir = path.resolve(__dirname);

var standard_input = process.stdin;

standard_input.setEncoding('utf-8');

console.log("Please type yes or no.");

standard_input.on('data', function (data) {
   if(data === 'yes'){
      console.log("OK I will.");
      process.exit();
   } else if (data === 'no') {
      console.log("OK I won't.");
      process.exit();
   } else {
      console.log("Please enter yes or no.");
   }
});

第一个提示 "Please type yes or no." 正确执行,我可以在命令行中输入,但是当我输入 yesno 时,它会以 else 提示响应:Please enter yes or no.

我尝试过yesYES'yes''YES',以及no的相同四种格式。我还尝试将if(data === 'yes') 行更改为所有四种格式以及if(data === 'yes\n'),以防输入抛出条件。

当我console.log(data) 时,它也会记录正确的数据。所以如果我输入yes,回调函数将记录yes。除了实际的 if/else 评估之外,它似乎工作正常,它只命中了最后一个 else 语句。

我目前在 Node.js 的 v8.11.1 上运行。

【问题讨论】:

  • 请注意,字符串将包含回车键作为换行符\n
  • 我在问题中提到我试过if(data === 'yes\n'),但还是不行。
  • 换个方式试试 - data.trim() === "yes" 似乎对我有用。
  • @jonrsharpe 这行得通!谢谢。

标签: node.js command-line command-line-interface


【解决方案1】:

正如@jonrsharpe 在 cmets 中指出的那样,在将 data'yes''no' 进行比较之前,使用 data.trim() 解决了这个问题。

以下是更正后的if/else 声明。

if(data.trim() === 'yes'){
  console.log("OK I will.");
  process.exit();
} else if (data.trim() === 'no') {
  console.log("OK I won't.");
  process.exit();
} else {
  console.log("Please enter yes or no.");
}

【讨论】:

    猜你喜欢
    • 2015-06-28
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2012-11-09
    • 2015-07-22
    • 2011-12-13
    相关资源
    最近更新 更多