地址
說(shuō)明
readline模塊提供了一個(gè)接口,從readable
流讀取一行數(shù)據(jù),比如process.stdin。其實(shí)就是,提供了一個(gè)交互,可輸入也可輸出。
基本用法
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
然后就是各種的監(jiān)聽(tīng)事件。如line
, 'close'等等。
rl.question('What do you think of Node.js? ', (answer) => {
// TODO: Log the answer in a database
console.log('Thank you for your valuable feedback:', answer);
rl.close();
});
最好看的莫過(guò)于prompt
了。
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: 'me> '
});
rl.prompt();
rl.on('line', (line) => {
//TODO your logic here
rl.prompt();
}).on('close', () => {
console.log('Have a great day!');
process.exit(0);
});
這樣就可以實(shí)現(xiàn)一種視覺(jué)效果
me> who you are?
me> 666
簡(jiǎn)單來(lái)說(shuō),就是多了一個(gè)前綴。
小結(jié)
readline基本沒(méi)怎么用過(guò)。在用戶交互方面還是有一定的作用的。可以基于這個(gè)模塊來(lái)寫(xiě)工具。