防止在节点readline中输出空行

时间:2019-05-07 19:38:09

标签: node.js stream readline

当我按住键盘上的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();
})

1 个答案:

答案 0 :(得分:0)

使用此

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

输入将被自动忽略并返回到开头

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();
})