我们如何从 Deno 的标准输入中获取值?
我不知道怎么用Deno.stdin
。
一个例子将不胜感激。
我们可以在 deno 中使用 prompt。
const input = prompt('Please enter input');
如果输入必须是数字。我们可以使用Number.parseInt(input)
;
Deno.stdin
是 type ,因此您可以通过提供as 缓冲区并调用File
来读取它Uint8Array
Deno.stdin.read(buf)
window.onload = async function main() {
const buf = new Uint8Array(1024);
/* Reading into `buf` from start.
* buf.subarray(0, n) is the read result.
* If n is instead Deno.EOF, then it means that stdin is closed.
*/
const n = await Deno.stdin.read(buf);
if (n == Deno.EOF) {
console.log("Standard input closed")
} else {
console.log("READ:", new TextDecoder().decode(buf.subarray(0, n)));
}
}
可以用or回答的简单确认:y
n
import { readLines } from "https://deno.land/std@0.76.0/io/bufio.ts";
async function confirm(question) {
console.log(question);
for await (const line of readLines(Deno.stdin)) {
if (line === "y") {
return true;
} else if (line === "n") {
return false;
}
}
}
const answer = await confirm("Do you want to go on? [y/n]");
或者,如果您想提示用户输入字符串:
import { readLines } from "https://deno.land/std@0.76.0/io/bufio.ts";
async function promptString(question) {
console.log(question);
for await (const line of readLines(Deno.stdin)) {
return line;
}
}
const userName = await promptString("Enter your name:");
我建议使用Input-Deno模块。这是文档中的一个示例:
// For a single question:
const input = new InputLoop();
const nodeName = await input.question('Enter the label for the node:');
// output:
// Enter the label for the node:
// Return Value:
// 'a'
我有一个 100% 纯 Deno 的解决方案,但没有经过深入测试
async function ask(question: string = '', stdin = Deno.stdin, stdout = Deno.stdout) {
const buf = new Uint8Array(1024);
// Write question to console
await stdout.write(new TextEncoder().encode(question));
// Read console's input into answer
const n = <number>await stdin.read(buf);
const answer = new TextDecoder().decode(buf.subarray(0, n));
return answer.trim();
}
const answer = await ask(`Tell me your name? `);
console.log(`Your name is ${answer}`);
以上部分代码取自Kevin Qian的回答
我有一个小型终端样本要使用 Deno TCP echo server进行测试。它是这样的:
private input = new TextProtoReader(new BufReader(Deno.stdin));
while (true) {
const line = await this.input.readLine();
if (line === Deno.EOF) {
console.log(red('Bye!'));
break;
} else {
// display the line
}
}
完整的项目在Github上。