【问题标题】:Why does this node CL generate multiple prompts?为什么这个节点CL会产生多个提示?
【发布时间】:2014-09-05 04:48:34
【问题描述】:

当直接使用标准输入/标准输出在命令行上工作时,我注意到节点中有一个奇怪的行为。该程序应该提示您输入一些文本,将文本附加到文件 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();

第二次输入后,提示将触发两次,然后是四次。 (不仅如此,我还会收到警告)

Enter text: foo
Enter text: bar
Enter text: Enter text: baz
Enter text: Enter text: Enter text: Enter text: qux

fp.txt 显示 1 foo、2 bar、4 baz 和 8 qux。有没有办法只使用 process.stdin 和 process.stdout 来保持单个文本输入循环?

【问题讨论】:

    标签: node.js stdin


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-04-19
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 2016-04-04
      相关资源
      最近更新 更多