【问题标题】:Can I print the current readline value after printing other content to the command line?将其他内容打印到命令行后,是否可以打印当前的 readline 值?
【发布时间】:2021-07-31 04:36:54
【问题描述】:

我有一个简单的 http 服务器,它返回 200 - 成功响应,还有一个 readline 函数,可以打印终端中输入的任何内容。

问题:有没有办法收集输入的内容并在下面重新打印,以便用户可以在服务器继续服务请求的同时继续输入?或者有没有更聪明的方法在 nodeJS 应用程序中结合标准输入和标准输出?

解释

服务器代码:

const http = require("http");
const readline = require("readline");

const host = "localhost";
const port = 8080;

const server = http.createServer(async (request, response) => {
  console.log("request received");
  response.writeHead(200);
  response.end("success");
});

server.listen(port, host, () => {
  console.log(`Listening on ${port}`);
});

const lineReader = readline.createInterface({
  input: process.stdin
});

lineReader.on("line", (line) => {
  console.log(`Received ${line}`);
});

如果我在命令行中输入一些内容,它会起作用:

[~/workspace/tests/async-prompt] node index.js
Listening on 8080
Something
Received Something

如果我访问服务器,它可以工作:

[~/workspace/tests/async-prompt] node index.js
Listening on 8080
request received

但是,当我在终端中输入时,如果有一个请求进来,它就会变得混乱:

[~/workspace/tests/async-prompt] node index.js
Listening on 8080
typingtypingtypingrequest received
typing
Received typingtypingtypingtyping

有没有办法在被其他打印到输出的东西打断时打印我正在输入的内容?我会对这样的事情感到满意:

[~/workspace/tests/async-prompt] node index.js
Listening on 8080
typingtypingtypingrequest received
typingtypingtyping_

【问题讨论】:

    标签: javascript node.js command-line


    【解决方案1】:

    我在这篇文章中找到了答案:Real Time Chat with NodeJS/Readline/SocketIO。我必须使用辅助函数从终端获取当前输入,然后清除该行,打印传入的输出,然后再次填充输入:

    const lineReader = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
      prompt: "",
    });
    
    const safeLog = (message, ...optionalParams) => {
      const currentlyTyped = lineReader.line;
      process.stdout.clearLine();
      process.stdout.cursorTo(0);
      if (optionalParams.length > 0){
        console.log(message, optionalParams);
      } else {
        console.log(message);
      }
      process.stdout.write(currentlyTyped);
    }
    
    const interval = setInterval(() => {
      safeLog("Logging on timeout")
    }, 2000);
    
    lineReader.on("SIGINT", () => process.exit());
    
    lineReader.on("line", (line) => {
      safeLog(`Received ${line}`);
    });
    
    

    请注意,当像这样使用 readline 时,ctrl-c(或 SIGINT)会杀死行阅读器,但不一定会杀死应用程序的其余部分,所以我为此添加了一个处理程序。

    【讨论】:

      猜你喜欢
      • 2011-12-04
      • 2020-08-11
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多