我需要知道,如果有可能通過通過標準輸入的每一個字輸入到迭代到使用JavaScript的程序。如果是這樣,我可以得到有關如何這樣做的任何線索?是否有可能通過Javascript來遍歷stdin中的每個單詞?
回答
假設你正在使用具有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.
在Node中,這不起作用 - 至少不可靠。 Node的'stdin'是一個'Buffer',而不是一個字符串。 – josh3736 2012-07-27 22:58:19
這太好了。但是我需要stdin來等於通過鍵盤輸入的內容。感謝您的良好開局! – Evan 2012-07-27 22:58:22
@Evan看到下面的答案http://stackoverflow.com/questions/5006821/nodejs-how-to-read-keystrokes-from-stdin?answertab=votes#tab-top – travis 2012-07-27 23:04:18
隨着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用完時(特別是進程地址空間)崩潰。
通過處理作爲標準輸入流,你能夠處理具有良好的性能任意大的投入,因爲你的腳本只在一時刻數據的小塊交易。缺點是複雜性顯着增加。
上面的代碼將工作在任何大小的輸入,如果某個單詞被減半塊之間斬不破。
極好的例子。 – 2012-07-28 04:13:16
- 1. 是否有可能通過py2neo遍歷所有節點
- 2. 是否有可能在JavaScript中功能性地遍歷對象?
- 3. 如何遍歷每個單詞,ms-word?
- 4. 是否有可能通過RegEx遍歷多行文本並在每個上下文HTML中包裝每行?
- 5. 遍歷單詞儘可能多re.search python
- 6. 是否有可能有多個STDIN流?
- 7. 是否有任何標準函數通過應用於單個值來遍歷謂詞?
- 8. 是否有可能通過詞性搜索Lucene索引中的單詞
- 9. 通過遍歷javascript中的每個節點來解析xml數據
- 10. 如何通過Char遍歷可能?
- 11. 如何遍歷word文檔中的每個單詞 - VBA宏
- 12. 是否有可能通過onclick添加dropzone表單javascript
- 13. 通過遍歷
- 14. 是否有更可讀(高效)的方式來遍歷ndarray?
- 15. 通過遞歸遍歷一個Javascript對象來累積路徑
- 16. 是否有可能通過空序列的逆序遍歷來唯一重構二叉樹?
- 17. 是否可以通過遍歷檢測變化?
- 18. 只能通過遍歷一個for循環來顯示數組
- 19. 的Javascript:通過遍歷數組
- 20. 是否可以遍歷JSON來查找屬性是否存在?
- 21. 是否有可能使用javascript或jquery遍歷div的樣式屬性?
- 22. 是否有可能通過Java中的Double來倍增BigInteger?
- 23. 是否有可能通過幾個類來分發NHibernate-Code-Mappings?
- 24. 找到樹的序遍歷和通過否定每隔數
- 25. 在c#中,是否有可能遍歷相同基類型的多個集合?
- 26. 預訂遍歷是否可能與後序遍歷的順序相同?
- 27. 通過XML遍歷
- 28. 通過遍歷Javascript中的整個表訪問tableRow的id值
- 29. 是否有可能通過EasyMock的
- 30. KeyError通過循環遍歷每個鍵的多個值
你使用什麼程序?你嘗試過stdin.split(/ \ s/g).forEach(YOUR_FUNCTION)嗎? – 2012-07-27 22:44:13
那麼我打算從頭開始編寫程序,我只是想知道是否可以這樣做? – Evan 2012-07-27 22:48:58
你在使用nodejs嗎?我會這樣認爲,但是我沒有在任何地方看到標籤。 – travis 2012-07-27 22:50:57