0
當使用stdin/stdout直接在命令行上工作時,我注意到節點中存在奇怪的行爲。這個程序應該提示你輸入一些文字,追加文本到一個文件fp.txt,然後提示你再做一次循環往復爲什麼此節點CL會生成多個提示?
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來保持單個文本輸入循環?