Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values from Deno stdin

Tags:

deno

How can we get values from standard input in Deno?

I don't know how to use Deno.stdin.

An example would be appreciated.

like image 422
benjamin Rampon Avatar asked Sep 19 '19 22:09

benjamin Rampon


3 Answers

A simple confirmation which can be answered with y or n:

import { readLines } from "https://deno.land/std/io/buffer.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/io/buffer.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:");
like image 147
Rotareti Avatar answered Nov 06 '22 22:11

Rotareti


We can use prompt in deno.

const input = prompt('Please enter input');

In case input has to be a number. We can use Number.parseInt(input);

like image 15
ADITYA KUMAR Avatar answered Nov 06 '22 23:11

ADITYA KUMAR


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)));
  }
}
like image 10
Kevin Qian Avatar answered Nov 06 '22 23:11

Kevin Qian