How can we get values from standard input in Deno?
I don\'t know how to use Deno.stdin
.
An example would be appreciated.
Deno.stdin
is of type File, thus you can read from it by providing a Uint8Array
as buffer and call 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)));
}
}
I have a small terminal sample to test with the Deno TCP echo server. It's something like:
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
}
}
The full project is on Github.
I have a solution 100% pure Deno, but not intensively tested
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}`);
Parts of the above code was taken from answer of Kevin Qian
A simple confirmation which can be answered with y
or 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]");
Or if you want to prompt the user for a string:
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:");
I would suggest using the Input-Deno module. This is an example from the docs:
// 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'