一个简单的是/否脚本会产生奇怪的行为 [英] A simple yes/no script yields weird behavior

查看:31
本文介绍了一个简单的是/否脚本会产生奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个简单的是/否脚本.

I am trying to implement a simple yes/no script.

一个函数运行,然后提示用户输入是否再次运行它.

A function runs, then the user is prompt to input whether or not to run it again.

如果用户输入y",则应重复该过程.

If the user inputs "y", then the procedure should repeat.

如果用户输入n",那么程序应该终止.

If the user inputs "n", then the procedure should terminate.

如果两者都不是,那么问题应该重复.

If neither, then the question should repeat.

这是我的代码:

function func(i) {
    console.log(i);
    ask(i + 1);
}

function ask(i) {
    process.stdout.write("again (y/n)?");
    process.stdin.on("data", function(data) {
        process.stdin.end();
        if (data.toString().trim() == "y")
            func(i);
        else if (data.toString().trim() != "n")
            ask(i);
    });
}

func(0);

不幸的是,该过程总是在第二次提出问题时终止.

Unfortunately, the process always terminates at the second time the question is asked.

我尝试删除 process.stdin.end() 部分,但我得到了一个非常奇怪的行为:

I tried removing the process.stdin.end() part, and I got a really weird behavior:

第一次输入y",问题被问了一次,函数运行了一次.

First time I input "y", the question is asked once and the function runs once.

第二次输入y",问题被问了两次,函数运行了两次.

Second time I input "y", the question is asked twice and the function runs twice.

第三次输入y",问题被问了三次,函数运行了三次.

Third time I input "y", the question is asked thrice and the function runs thrice.

此外,在某些时候我开始收到此错误:

In addition, at some point I start getting this error:

(节点:12336)MaxListenersExceededWarning:检测到可能的 EventEmitter 内存泄漏.添加了 11 个数据侦听器.使用emitter.setMaxListeners()增加限制

(node:12336) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 data listeners added. Use emitter.setMaxListeners() to increase limit

这里可能会发生什么?

推荐答案

process.stdin.end();

阻止进一步的输入,并且(在这里)有效地结束程序.因此,一旦一切都完成,您将只想调用它一次.

prevents further input, and (here) effectively ends the program. So, you'll want to call it only once, once everything is done. The

process.stdin.on

命令在用户按下回车"时添加一个监听器.如果多次调用此方法,则会添加多个侦听器.

command adds a listener to when the user presses "enter". If you call this multiple times, multiple listeners will be added.

因此,您可能会考虑仅添加 一个 侦听器,如果响应为 n,则调用 process.stdin.end();:

So, you might consider adding just one listener, calling process.stdin.end(); if the response is n:

let i = 0;
function func() {
  console.log(i);
  i++;
  ask();
}
process.stdin.on("data", function(data) {
  if (data.toString().trim() === "y")
    func(i);
  else if (data.toString().trim() === "n")
    process.stdin.end();
  else
    ask();
});
function ask() {
  process.stdout.write("again (y/n)?");
}

func();

输出示例:

PS D:\Downloads> node foo.js
0
again (y/n)?
again (y/n)?
again (y/n)?y
1
again (y/n)?y
2
again (y/n)?
again (y/n)?y
3
again (y/n)?n
PS D:\Downloads>

这篇关于一个简单的是/否脚本会产生奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆