2014-09-05 35 views
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來保持單個文本輸入循環?

回答

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(); 
} 
相關問題