require('readline') 逐行讀取可用於從命令行讀取、從文件逐行讀取寫入等html
const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
經過 readline.createInterface(options) 方法建立一個新的 readline.Interface 實例來實現逐行讀取。node
options
<Object>linux
input
<Readable> 要監聽的可讀流。該選項是必需的。output
<Writable> 要寫入逐行讀取數據的可寫流。completer
<Function> 一個可選的函數,用於 Tab 自動補全。terminal
<boolean> 若是 input
和 output
應被看成一個 TTY,且要寫入 ANSI/VT100 轉換的代碼,則設爲 true
。 默認爲實例化時在 output
流上檢查 isTTY
。historySize
<number> 保留的歷史行數的最大數量。 設爲 0
可禁用歷史記錄。 該選項只有當 terminal
被用戶或內部 output
設爲 true
時纔有意義,不然歷史緩存機制不會被初始化。 默認爲 30
。prompt
- 要使用的提示字符串。默認爲 '> '
。crlfDelay
<number> 若是 \r
與 \n
之間的延遲超過 crlfDelay
毫秒,則 \r
和 \n
都會被看成換行分隔符。 crlfDelay
will be coerced to a number no less than 100
. It can be set to Infinity
, in which case \r
followed by \n
will always be considered a single newline (which may be reasonable for reading files with \r\n
line delimiter). 默認爲 100
毫秒。removeHistoryDuplicates
<boolean> If true
, when a new input line added to the history list duplicates an older one, this removes the older line from the list. 默認爲 false
。
rl.close() 方法會關閉 readline.Interface 實例,且撤回對 input 和 output 流的控制。 被調用時,'close' 事件會被觸發。api
rl.pause() 方法會暫停 input 流,且稍後須要時可被恢復。緩存
preserveCursor <boolean> 若是爲 true,則阻止光標落點被設爲 0less
rl.prompt() 方法會在 output 流中新的一行寫入 readline.Interface 實例配置後的 promptide
若是 input 流已被暫停,則 rl.resume() 方法會恢復 input 流。函數
rl.write('刪除這個!'); // 模擬 Ctrl+u 刪除寫入的前一行。 rl.write(null, { ctrl: true, name: 'u' });
當 'close' 事件被觸發時,readline.Interface 實例應當被視爲已結束ui
每當 input 流接收到接收行結束符(\n、\r 或 \r\n)時觸發 'line' 事件。this
一般發生在用戶按下 <Enter> 鍵或 <Return> 鍵。 監聽器函數被調用時會帶上一個包含接收的那一行輸入的字符串。
rl.on('line', (input) => { console.log(`接收到:${input}`); });
當如下之一發生時觸發 'pause'
事件:
監聽器函數被調用時不傳入任何參數。
每當 input
流被恢復時觸發 'resume'
事件。
監聽器函數被調用時不傳入任何參數。
每當 input
流接收到一個 <ctrl>-C
輸入(一般被稱爲 SIGINT
)時,觸發 'SIGINT'
事件。 當 input
流接收到一個 SIGINT
時,若是沒有註冊 'SIGINT'
事件監聽器,則 'pause'
事件會被觸發。
監聽器函數被調用時不傳入任何參數。
當一個 Node.js 進程使用 <ctrl>-Z
(也就是 SIGTSTP
)移入後臺以後再使用 fg(1p) 移回前臺時,觸發 'SIGCONT'
事件。
若是 input
流在 SIGTSTP
請求以前被暫停,則事件不會被觸發。
監聽器函數被調用時不傳入任何參數。
每當 input
流接收到一個 <ctrl>-Z
輸入(一般被稱爲 SIGTSTP
)時,觸發 'SIGTSTP'
事件。 當 input
流接收到一個 SIGTSTP
時,若是沒有註冊 'SIGTSTP'
事件監聽器,則 Node.js 進程會被髮送到後臺。
當程序使用 fg(1p) 恢復時,'pause'
和 SIGCONT
事件會被觸發。 這可被用來恢復 input
流。
若是 input
流在進程被髮送到後臺以前被暫停,則 'pause'
和 SIGCONT
事件不會被觸發。
監聽器函數被調用時不傳入任何參數。