![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
readline-sync
Advanced tools
The readline-sync package is a Node.js module that allows synchronous readline interface for reading input from the console. It is designed to make it easy to prompt and get user input in a synchronous manner without the complexities of asynchronous callbacks. This package is particularly useful for CLI (Command Line Interface) applications where you need to ask questions, get user input, or display messages sequentially.
Basic Input
This feature allows you to prompt the user for input and store their response. The `question` method displays a message to the user and waits for their input.
const readlineSync = require('readline-sync');
let userName = readlineSync.question('May I have your name? ');
console.log('Hi ' + userName + '!');
Password Input
This feature is used for password or sensitive information inputs. It hides the user's input on the screen to protect sensitive information.
const readlineSync = require('readline-sync');
let password = readlineSync.question('Enter your password: ', {
hideEchoBack: true // The typed text on screen is hidden by `*` (default).
});
Multiple Choice List
This feature allows you to present a list of options to the user and let them choose. It is useful for menus or any choice-based interaction.
const readlineSync = require('readline-sync');
let animals = ['Lion', 'Elephant', 'Crocodile', 'Giraffe', 'Hippo'],
index = readlineSync.keyInSelect(animals, 'Which animal?');
console.log('Ok, ' + animals[index] + ' goes to your room.');
Inquirer.js is a common alternative to readline-sync with a more extensive set of features for asking questions, parsing input, validating answers, and managing hierarchical prompts. Unlike readline-sync, which is synchronous, Inquirer.js is asynchronous and based on promises, making it more suitable for complex CLI applications that require non-blocking operations.
Prompt is another alternative that offers a simple interface for creating and managing a command-line prompt. It is less feature-rich compared to readline-sync and Inquirer.js but provides a straightforward way to get user input asynchronously. It supports validation, default values, and custom prompt types.
Synchronous Readline for interactively running.
The interface is used with process.stdin
and process.stdout
in order to accept user input.
var readlineSync = require('readline-sync');
var answer = readlineSync.question('What is your favorite food? :');
console.log('Oh, so your favorite food is ' + answer);
npm install readline-sync
currentValue = readlineSync.setPrompt([prompt])
Sets the prompt, for example when you run node
on the command line, you see >
, which is node's prompt.
prompt
may be string, or may not be (e.g. number, Date, Object, etc.). This is converted to string (i.e. toString
method is called) before it is displayed every time.
For example: [foo-directory]#
like a bash
// Object that has toString method.
readlineSync.setPrompt({toString: function() {
return '[' + require('path').basename(process.cwd()) + ']# ';
}})
line = readlineSync.prompt([options])
Readies readline for input from the user, putting the current setPrompt
options on a new line, giving the user a new spot to write.
If {noEchoBack: true}
is specified to options
, echo back is avoided. It is used to hide the secret text (e.g. password) which is typed by user on screen.
line = readlineSync.question([query[, options]])
Displays the query
to the user, and then returns the user's response after it has been typed.
query
may be string, or may not be (e.g. number, Date, Object, etc.). This is converted to string (i.e. toString
method is called) before it is displayed.
If {noEchoBack: true}
is specified to options
, echo back is avoided. It is used to hide the secret text (e.g. password) which is typed by user on screen.
currentValue = readlineSync.setEncoding([encoding])
Set the encoding method of input (user's response) and output (prompt
and question
). Defaults to 'utf8'.
readlineSync.setPrint([funcPrint])
The specified Function is called when any output (prompt
and question
). Defaults to undefined
.
The Function is given two arguments the output text and encoding
.
For example, this is used to pass plain texts to Logger, when texts are colored.
var readlineSync = require('readline-sync'),
user, pw, cmd;
require('colors');
readlineSync.setPrint(function(display, encoding) {
logger.log(display.stripColors); // remove control characters
});
console.log('Your account required.'.grey);
user = readlineSync.question('USER NAME'.white.inverse + ': ');
pw = readlineSync.question('PASSWORD'.white.inverse + ': ', {noEchoBack: true});
// Authorization ...
console.log(('Welcome, ' + user + '!').green.bold);
readlineSync.setPrompt('> '.bold.red);
cmd = readlineSync.prompt();
The easy way to control the flow of task runner by the user's response:
If you want to control the flow of task runner (e.g. Grunt), call readlineSync in a task callback that is called by task runner. Then the flow of tasks is paused and it is controlled by user.
Example: by using grunt-task-helper
$ grunt
Running "fileCopy" task
Files already exist:
file-a.png
file-b.js
Overwrite? (y/n) :y
file-a.png copied.
file-b.js copied.
Done.
Gruntfile.js
grunt.initConfig({
taskHelper: {
fileCopy: {
options: {
handlerByTask: function() {
// Abort the task if user don't want.
return readlineSync.question('Overwrite? (y/n) :')
.toLowerCase() === 'y';
// Or process.exit()
},
filesArray: []
},
...
}
},
copy: {
fileCopy: {
files: '<%= taskHelper.fileCopy.options.filesArray %>'
}
}
});
The your Node and OS may not support interactively reading from stdin. The stdin interfaces are different by platforms.
If in those platforms, an error is thrown.
try {
answer = readlineSync.question('What is your favorite food? :');
} catch (e) {
console.error(e);
process.exit(1);
}
readlineSync tries reading from stdin by shell if it is needed. And, it use "piping via files" for synchronous running.
As everyone knows, "piping via files" is no good. It blocks event loop and a process. It may make your script be slow.
Why did I choose it? :
Someday, I may rewrite readlineSync to use child_process.execSync, or safety module.
stty
in read.sh.setPrompt()
and setEncoding()
return current value.setPrompt()
and question()
accept the value which is not string too (e.g. number, Date, Object, etc.).options.noEchoBack
.setPrint()
.FAQs
Synchronous Readline for interactively running to have a conversation with the user via a console(TTY).
The npm package readline-sync receives a total of 1,293,621 weekly downloads. As such, readline-sync popularity was classified as popular.
We found that readline-sync demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.