在寫算法題的時候,基本上都需要輸入輸出語句,在大多數練題網站上當想用js書寫算法題時,發現不知道怎么輸入,其實Node是提供了一個readline模塊來實現此功能的
tip
筆者用過的練題網站只有leetcode在使用js書寫時只需要實現功能函數就行,就不需要考慮如何從鍵盤錄入內容
簡單使用
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
// 監聽鍵入回車事件
rl.on('line', (str) => {
// str即為輸入的內容
if (str === 'close') {
// 關閉逐行讀取流 會觸發關閉事件
rl.close()
}
console.log(str);
})
// 監聽關閉事件
rl.on('close', () => {
console.log('觸發了關閉事件');
})
假設上面的文件叫read.js,接下來我們直接輸入下面運行
node read.js
上面的邏輯是輸入字符串 close時退出程序
感覺並沒有其它語言用起來那么安逸,比如:
- C++:
cin>>param - C:
scanf("%s",¶m) - C#:
param = Console.ReadLine() - ...等等
怎樣才能變得向上面那樣用起來輸入一點呢?我們為上面代碼包裝一下
封裝
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
/**
* 讀入一行
*/
function readLine() {
return new Promise(resolve => {
rl.on('line', (str) => {
resolve(str)
})
})
}
/**
* 退出逐行讀取
*/
function close() {
rl.close()
}
module.exports = {
readLine,
close
}
我們在編寫一個新的test.js,上面的叫read.js 放在同一目錄下
const { readLine, close } = require('./read')
/**
* 運行的main函數
**/
async function main() {
let i = await readLine();
while (+i !== 0) {
console.log(`你輸入的是${i}`);
i = await readLine();
}
close();
}
// 調用執行
main();
現在用起來就方便多了,只需要在函數結束時加上close不然不會退出
