在RingoJS中有一個function,名爲read
,它允許您讀取整個流直到到達末尾。這在您製作命令行應用程序時很有用。舉例如下,你可以寫一個tac
program:如何讀取node.js中的整個文本流?
#!/usr/bin/env ringo
var string = system.stdin.read(); // read the entire input stream
var lines = string.split("\n"); // split the lines
lines.reverse(); // reverse the lines
var reversed = lines.join("\n"); // join the reversed lines
system.stdout.write(reversed); // write the reversed lines
這可以讓你啓動一個程序並運行tac
命令。然後你,你希望鍵入儘可能多的行,你就大功告成之後,你可以按Ctrl鍵+(在Windows或按Ctrl +ž)d信號的end of transmission。
我想在node.js中做同樣的事情,但我找不到可以這樣做的任何函數。我想到了用readSync
function從fs
庫模擬如下,但無濟於事:
fs.readSync(0, buffer, 0, buffer.length, null);
的file descriptor for stdin(第一個參數)是0
。所以它應該讀取鍵盤上的數據。相反,它給了我下面的錯誤:
Error: ESPIPE, invalid seek
at Object.fs.readSync (fs.js:381:19)
at repl:1:4
at REPLServer.self.eval (repl.js:109:21)
at rli.on.self.bufferedCmd (repl.js:258:20)
at REPLServer.self.eval (repl.js:116:5)
at Interface.<anonymous> (repl.js:248:12)
at Interface.EventEmitter.emit (events.js:96:17)
at Interface._onLine (readline.js:200:10)
at Interface._line (readline.js:518:8)
at Interface._ttyWrite (readline.js:736:14)
你會如何同步收集在輸入文本流中的所有數據,並恢復它作爲Node.js的一個字符串?一個代碼示例會非常有幫助。
您無法在異步流中同步讀取。無論如何,你爲什麼要? – tjameson
我正在嘗試做同樣的事情。原因是在我的程序中創建一個交互選項,這有很多原因。一個異步閱讀器不會幫助太多。 – ton
這裏有一個方法https://www.npmjs。com/package/readline-sync:http://stackoverflow.com/questions/8452957/synchronously-reading-stdin-in-windows/27931290#27931290 – ton