Node.js 为什么此节点会生成多个提示?

Node.js 为什么此节点会生成多个提示?,node.js,stdin,Node.js,Stdin,当直接使用stdin/stdout在命令行上工作时,我注意到node中有一个奇怪的行为。这个程序应该提示您输入一些文本,将文本附加到fp.txt文件中,然后提示您无限期地再次输入 var fs = require('fs'), stdin = process.stdin, stdout = process.stdout; function prompt() { stdout.write('Enter text: '); stdin.resume(); stdin.setEncodi

当直接使用stdin/stdout在命令行上工作时,我注意到node中有一个奇怪的行为。这个程序应该提示您输入一些文本,将文本附加到fp.txt文件中,然后提示您无限期地再次输入

var fs = require('fs'), stdin = process.stdin, stdout = process.stdout;

function prompt() {
  stdout.write('Enter text: ');
  stdin.resume();
  stdin.setEncoding('utf8');
  stdin.on('data', enter);
}

function enter(data) {
  stdin.pause(); // this should terminate stdin
  fs.open('fp.txt', 'a', 0666, function (error, fp) {   
    fs.write(fp, data, null, 'utf-8', function() {
        fs.close(fp, function(error) {
            prompt();
        });
      });
  });
}

prompt();
第二次输入后,提示符将触发两次,然后触发四次。(除此之外,我还收到了一条警告)


fp.txt显示1个foo、2个bar、4个baz和8个qux。是否有一种方法可以仅使用process.stdin和process.stdout来保持单个文本输入循环的运行?

每次调用
prompt()
时,您都要向
stdin
添加一个新的事件侦听器。然后,每次您在
stdin
流中输入新内容时,它都会调用您先前添加的所有事件侦听器

您应该在脚本开始时调用它一次(您也可以将
setEncoding
放在那里):

Enter text: foo
Enter text: bar
Enter text: Enter text: baz
Enter text: Enter text: Enter text: Enter text: qux
var fs = require('fs'), stdin = process.stdin, stdout = process.stdout;

stdin.setEncoding('utf8');
stdin.on('data', enter);

function prompt() {
  stdout.write('Enter text: ');
  stdin.resume();
}