[英]Fixed position command prompt in Node.js
有沒有辦法將命令提示符(只是一個question
提示或類似的東西)固定到終端的底部,並使用Node.js記錄它上面的輸出。
一個非常糟糕的例子:
Your favourite food is sushi.
Your favourite food is chicken.
Your favourite food is okra.
--> What is your favourite food?
基本上,我希望用戶始終能夠鍵入,並在輸入上方回顯輸入。
interface.question("What is your favourite food?", function(answer) {
// output the answer above where this prompt was
// and somehow keep this same prompt where is is
});
我希望使用它的特定應用程序是一個簡單的IRC客戶端,我有一個供用戶鍵入的位置,並且輸出所有輸出(用戶鍵入的內容,以及其他人也鍵入的內容)用戶正在打字。 下圖中的線是虛構的。
----------------------------------------------------------------------
| |
| |
| |
| |
| |
| |
| |
| Stuff |
| Stuff |
| Stuff |
----------------------------------------------------------------------
| --> The user can type here |
----------------------------------------------------------------------
process.stdout.write("\x1Bc")
console.log(Array(process.stdout.rows + 1).join('\n'));
const myRL = require("serverline")
myRL.init()
myRL.getRL().question("What is your favourite food? ", function(answer) {
console.log(`Your favourite food is ${answer}.`)
});
function main() {
let i = 0
setInterval(function() {
const num = () => Math.floor(Math.random() * 255) + 1
i++
console.log(i + " " + num() + "." + num() + "." + num() + " user connected.")
}, 700)
}
main()
舊版 :
好吧,我正在使用詢問者來解決這類問題..它已經解決了所有這些問題。它很容易使用,你有不同類型的propmt類型。
這里有一個litle示例來形成doc:
var inquirer = require('inquirer');
inquirer.prompt([/* Pass your questions in here */]).then(function (answers) {
// Use user feedback for... whatever!!
});
這是一個簡單的解決方案(在macos上使用node v6.4.0進行測試):
const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);
// Logs a message keeping prompt on last line
function log(message) {
readline.cursorTo(process.stdout, 0);
console.log(message);
rl.prompt(true);
}
// Testing the solution
rl.question('Enter something...:', userInput => {
log('You typed ' + userInput);
rl.close();
});
log('this should appear above the prompt');
setTimeout(
() => log('this should appear above the prompt'),
1000
);
只需使用readline核心模塊:
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What do you think of node.js? ", function(answer) {
console.log("Thank you for your valuable feedback:", answer);
rl.close();
});
這將解決您的問題:
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var fav_foods = [];
var ask_question = function() {
rl.question("What is your favourite food? ", function(answer) {
fav_foods.push(answer)
fav_foods.forEach(function (element) {
console.log("Your favourite food is " + element)
})
ask_question()
});
}
ask_question()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.