如何在TypeScript中接收用户的控制台输入?
例如,在Python中,我将使用:
userInput = input("Enter name: ")
Run Code Online (Sandbox Code Playgroud)
TypeScript中的等效项是什么?
TypeScript 仅向 JavaScript 添加了可选的静态类型和转译功能。它是一个纯粹的编译时工件;在运行时,没有 TypeScript,这就是为什么这个问题是关于 JavaScript,而不是 TypeScript。
如果您在谈论从控制台接受输入,那么您可能在谈论一个node.js应用程序。在从控制台以交互方式读取值中,解决方案是使用标准输入:
var stdin = process.openStdin();
stdin.addListener("data", function(d) {
// note: d is an object, and when converted to a string it will
// end with a linefeed. so we (rather crudely) account for that
// with toString() and then substring()
console.log("you entered: [" + d.toString().trim() + "]");
});
Run Code Online (Sandbox Code Playgroud)
在浏览器中,您将使用提示:
var userInput = prompt('Please enter your name.');
Run Code Online (Sandbox Code Playgroud)
在节点上,您可以使用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();
});
Run Code Online (Sandbox Code Playgroud)
您可以使用readline节点模块。请参阅节点文档中的readline。
要在TypeScript中导入readline,请使用asterisk(*)字符。例如:
import * as readline from 'readline';
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Is this example useful? [y/n] ', (answer) => {
switch(answer.toLowerCase()) {
case 'y':
console.log('Super!');
break;
case 'n':
console.log('Sorry! :(');
break;
default:
console.log('Invalid answer!');
}
rl.close();
});
Run Code Online (Sandbox Code Playgroud)
如果有人正在寻找更新且简洁的版本......
我正在使用“readline”包,因此以yarn add readlineor开头npm i readline。
首先,将其放入单独的文件中(即“question.ts”)
import {createInterface} from "readline";
const rl = createInterface({
input: process.stdin,
output: process.stdout
});
const question = (questionText: string) =>
new Promise<string>(resolve => rl.question(questionText, resolve))
.finally(() => rl.close());
export default question;
Run Code Online (Sandbox Code Playgroud)
进而
import question from "./question"
const name = await question("What is your name?");
const answer = await question("Are you sure? (y/N) ")
.then(answer => answer.toLowerCase() == 'y')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14584 次 |
| 最近记录: |