2012-07-27 36 views
0

我需要知道,如果有可能通過通過標準輸入的每一個字輸入到迭代到使用JavaScript的程序。如果是這樣,我可以得到有關如何這樣做的任何線索?是否有可能通過Javascript來遍歷stdin中的每個單詞?

+1

你使用什麼程序?你嘗試過stdin.split(/ \ s/g).forEach(YOUR_FUNCTION)嗎? – 2012-07-27 22:44:13

+0

那麼我打算從頭開始編寫程序,我只是想知道是否可以這樣做? – Evan 2012-07-27 22:48:58

+1

你在使用nodejs嗎?我會這樣認爲,但是我沒有在任何地方看到標籤。 – travis 2012-07-27 22:50:57

回答

0

假設你正在使用具有console.log的環境和標準輸入是一個字符串,那麼你就可以做到這一點。

輸入:

var stdin = "I hate to write more than enough."; 

stdin.split(/\s/g).forEach(function(word){ 
    console.log(word) 
}); 

輸出:

I 
hate 
to 
write 
more 
than 
enough. 
+0

在Node中,這不起作用 - 至少不可靠。 Node的'stdin'是一個'Buffer',而不是一個字符串。 – josh3736 2012-07-27 22:58:19

+0

這太好了。但是我需要stdin來等於通過鍵盤輸入的內容。感謝您的良好開局! – Evan 2012-07-27 22:58:22

+0

@Evan看到下面的答案http://stackoverflow.com/questions/5006821/nodejs-how-to-read-keystrokes-from-stdin?answertab=votes#tab-top – travis 2012-07-27 23:04:18

2

隨着Node

var stdin = process.openStdin(); 
var buf = ''; 

stdin.on('data', function(d) { 
    buf += d.toString(); // when data is received on stdin, stash it in a string buffer 
         // call toString because d is actually a Buffer (raw bytes) 
    pump(); // then process the buffer 
}); 

function pump() { 
    var pos; 

    while ((pos = buf.indexOf(' ')) >= 0) { // keep going while there's a space somewhere in the buffer 
     if (pos == 0) { // if there's more than one space in a row, the buffer will now start with a space 
      buf = buf.slice(1); // discard it 
      continue; // so that the next iteration will start with data 
     } 
     word(buf.slice(0,pos)); // hand off the word 
     buf = buf.slice(pos+1); // and slice the processed data off the buffer 
    } 
} 

function word(w) { // here's where we do something with a word 
    console.log(w); 
} 

處理標準輸入是不是一個簡單的字符串split要複雜得多,因爲節點提出了標準輸入作爲Stream (它發出我的大塊來自Buffer s)的數據,而不是字符串。 (它確實與網絡流和文件I/O同樣的事情。)

這是一件好事,因爲標準輸入可以任意大。考慮一下如果你將一個多GB的文件傳送到你的腳本中會發生什麼。如果它首先將stdin加載到一個字符串中,它首先需要很長時間,然後在RAM用完時(特別是進程地址空間)崩潰。

通過處理作爲標準輸入流,你能夠處理具有良好的性能任意大的投入,因爲你的腳本只在一時刻數據的小塊交易。缺點是複雜性顯着增加。

上面的代碼將工作在任何大小的輸入,如果某個單詞被減半塊之間斬不破。

+0

極好的例子。 – 2012-07-28 04:13:16

相關問題