【发布时间】: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 来保持单个文本输入循环?
【问题讨论】: