Командная строка с фиксированной позицией в 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 |
----------------------------------------------------------------------
Ответы
Ответ 1
![enter image description 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()
Старая версия:
https://stackoverflow.com/posts/24519813/revisions
Ответ 2
Ну, я использую inquirer для решения таких проблем.. У него уже есть все эти проблемы.. Это легко для использования, и у вас есть разные типы propmt.
Здесь пример litle из документа:
var inquirer = require('inquirer');
inquirer.prompt([/* Pass your questions in here */]).then(function (answers) {
// Use user feedback for... whatever!!
});
Ответ 3
Вот простое решение (проверено с помощью node v6.4.0 на macos):
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
);
Ответ 4
просто используйте 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()