【问题标题】:Prevent empty lines from output in node readline防止在节点 readline 中输出空行
【发布时间】:2019-05-07 19:38:08
【问题描述】:

当我按住键盘上的 ENTER 时,readline 模块将向我的可写流输出空行(在本例中为 process.stdout)。

但由于我不想让空行弄乱我的控制台,我想以某种方式阻止它被输出。

我可以使用一些东西来过滤掉我的信息流中的空行吗?也许使用某种转换流?

const readline = require("readline");

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

rl.on("line", (line) => {
  if(line.trim().length === 0) {
    // don't output anything, but it is already too late because it is already written to stream :'-(
  }
  rl.prompt();
})

【问题讨论】:

    标签: node.js stream readline


    【解决方案1】:

    使用这个

       readline.cursorTo(process.stdout, 0,0);
    

    enter会自动被忽略,回到开头

    https://nodejs.org/api/readline.html#readline_readline_clearline_stream_dir

    const readline = require("readline");
    
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
      removeHistoryDuplicates: true
    });
    
    
    const enterPressed=(line)=>{
        return line.replace(/[^a-zA-Z]/g, "").trim().length === 0
    }
    
    rl.on("line", (line) => {
    
      if(enterPressed(line)) {
         readline.cursorTo(process.stdout, 0,0);
      }
      rl.prompt();
    })
    

    【讨论】:

    • 这条线的真正含义是什么? return line.replace(/[^a-zA-Z]/g, "").trim().length === 0
    • 只测试输入被按下删除所有非字母字符
    • 似乎不起作用。好吧,它会在此之前删除所有可见的控制台输出。我拍了一张gif:i.imgur.com/1QrgWGw.gif
    • readline.cursorTo(, 0, . 将 NUMBER_OF_LINES 设置为 0 的最后一行
    • 能不能拿到最后一行?我在节点中寻找一种方法,但找不到。 :-(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2015-08-03
    相关资源
    最近更新 更多