READLINES-SYNC IN NODE JS

READLINES-SYNC IN NODE JS

As my first nodejs program, i had to make a cli quiz app which includes taking the input from the user . As there are many input methods, i used readline-sync .

ReadlineSync in node

Synchronous Readline for interactively running to have a conversation with the user via a console(TTY). readlineSync tries to let your script have a conversation with the user via a console, even when the input/output stream is redirected like your-script bar.log. A simple readlineSync code snippet will look like this

var readlineSync = require('readline-sync'); // Wait for user's response. var userName = readlineSync.question('May I have your name? '); console.log('Hi ' + userName + '!');

Above code snippet will simply ask for the user name as the input which will be stored in userName variable. For the input,it will display the 'May I have your name? ' as a message on the console and then the user will input the value as his/her name. Then console will display a welcome message along with username that the user entered.

May I have your name? CookieMonster Hi CookieMonster!

the console will look like this after executing the above snippet. Here "CookieMonster" is the name/input entered and look how input is taken along with displaying the message"May I have your name?".

readline sync for displaying a list:

var readlineSync = require('readline-sync'), animals = ['Lion', 'Elephant', 'Crocodile', 'Giraffe', 'Hippo'], index = readlineSync.keyInSelect(animals, 'Which animal?'); console.log('Ok, ' + animals[index] + ' goes to your room.');

this will generate the below output in the console:

[1] Lion [2] Elephant [3] Crocodile [4] Giraffe [5] Hippo [0] CANCEL

Which animal? [1...5 / 0]: 2 Ok, Elephant goes to your room.