deno get console input code example
Example 1: deno stdin
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}`);
Example 2: deno stdin
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)));
}
}