Readline:逐行读取三个输入,如果为true,则循环

时间:2019-04-19 17:00:00

标签: javascript node.js

我正在形成具有以下结构的输入:

var nodeArray = [
  {
    position: null,
    value: null
  },
  {
    position: null,
    value: null
  },
  // ...
]

逐行读取用户输入。下表中的每一行都是prompt中的rl.setPrompt(prompt)自变量,用于单次迭代,

  1. 插入要插入此节点的位置>
  2. 插入此节点的值>
  3. 您要插入另一个节点>
    • 如果Yes,循环... 从步骤1重新开始
    • 如果No,请解决promise并关闭rl

根据对node.js的了解,我能够为这样的简单结构编写代码:

var array = [
  value1,
  value2,
  value3,
  //...
]

用户输入以形成array的代码:

input.js

'use strict';                                                         

const readline = require('readline');                                 

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

module.exports = {
  init : async function(arr) {                                        
    this.arr = arr;
    const pr = await this.userInputOn();                              
    return pr;                                                        
  },                                                                  

  promptUpdater : function() {
    rl.setPrompt(`Insert ${this.arr.length}th array Element> `);      
    rl.prompt();                                                      
  },                                                                  

  userInputOn : function() {
    return new Promise((resolve, reject) =>  {                        
      this.promptUpdater();
      rl.on('line', (line) => {
        if(line === "close") resolve(this.arr);                       
        else {
          this.arr.push(+line);                                       
          this.promptUpdater();                                       
        }                                                             
      });                                                             
    });                                                               
  },                                                                  
}

使用 input.js 代码的代码:

main.js

'use strict';

const stdIn = require('input');

const input = stdIn.init([]);

input.then(function fulfilled(response) {
  // do something with response
});

我无法扩展input.js代码以满足我对形成nodeArray结构的要求。另外,此代码有一些故障,例如,它永远不会关闭rl

1 个答案:

答案 0 :(得分:2)

编写异步代码时,应始终尝试将尽可能小的任务包装到Promise中。在这种情况下,将是:提示问题,等待答案。因为我们只想听一个答案,所以我们只使用.once而不是.on

  function prompt(question) {
   return new Promise((resolve) => {
    rl.setPrompt(question);
    rl.prompt();
    rl.once("line", resolve);
   });
 }

现在我们已经有了,创建一个节点很简单:

  async function createNode() {
   return {
    position: await prompt("Position?"),
    value: await prompt("Value?"),
  };
 }

循环也很简单(如果我们使用异步/等待),并且不需要任何递归:

 async function createNodes() {
   const result = [];
   while(true) {
     result.push(await createNode());
     if(await prompt("Continue? Yes / No") === "No")
       break;
   }
   return result;
 }