Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
The 'prompt' npm package is a powerful tool for creating command-line interfaces (CLI) that can interact with users by asking questions and receiving input. It supports various types of prompts, validation, and asynchronous operations.
Basic Prompt
This feature allows you to prompt the user for basic input. The example code asks for a username and email, then logs the input to the console.
const prompt = require('prompt');
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
if (err) { return onErr(err); }
console.log('Command-line input received:');
console.log(' Username: ' + result.username);
console.log(' Email: ' + result.email);
});
function onErr(err) {
console.log(err);
return 1;
}
Validation
This feature allows you to validate user input based on a schema. The example code ensures that the age input is a number.
const prompt = require('prompt');
prompt.start();
const schema = {
properties: {
age: {
pattern: /^[0-9]+$/,
message: 'Age must be a number',
required: true
}
}
};
prompt.get(schema, function (err, result) {
if (err) { return onErr(err); }
console.log('Command-line input received:');
console.log(' Age: ' + result.age);
});
function onErr(err) {
console.log(err);
return 1;
}
Asynchronous Prompts
This feature allows you to handle prompts asynchronously using async/await. The example code prompts for a username and email, then logs the input.
const prompt = require('prompt');
prompt.start();
async function getUserInput() {
try {
const result = await prompt.get(['username', 'email']);
console.log('Command-line input received:');
console.log(' Username: ' + result.username);
console.log(' Email: ' + result.email);
} catch (err) {
console.error(err);
}
}
getUserInput();
Inquirer.js is a collection of common interactive command-line user interfaces. It provides a more extensive set of features compared to 'prompt', including support for different types of prompts (e.g., list, checkbox), better handling of nested prompts, and more customization options.
Readline-sync is a synchronous library for reading user input from the command line. Unlike 'prompt', it does not support asynchronous operations but is simpler to use for straightforward input tasks.
Enquirer is a stylish, user-friendly library for creating interactive CLI prompts. It offers a rich set of features similar to 'inquirer' but focuses more on customization and aesthetics.
A beautiful command-line prompt for node.js
curl http://npmjs.org/install.sh | sh
[sudo] npm install prompt
Using node-prompt is relatively straight forward. There are two core methods you should be aware of: prompt.get()
and prompt.addProperties()
. There methods take strings representing property names in addition to objects for complex property validation (and more). There are a number of examples that you should examine for detailed usage.
Getting started with node-prompt
is easy. Lets take a look at examples/simple-prompt.js
:
var prompt = require('prompt');
//
// Start the prompt
//
prompt.start();
//
// Get two properties from the user: username and email
//
prompt.get(['username', 'email'], function (err, result) {
//
// Log the results.
//
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
})
This will result in the following command-line output:
$ node examples/simple-prompt.js
prompt: username: some-user
prompt: email: some-user@some-place.org
Command-line input received:
username: some-user
email: some-user@some-place.org
In addition to prompting the user with simple string prompts, there is a robust API for getting and validating complex information from a command-line prompt. Here's a quick sample:
var properties = [
{
name: 'name',
validator: /^[a-zA-Z\s\-]+$/,
warning: 'Name must be only letters, spaces, or dashes',
empty: false
},
{
name: 'password',
hidden: true
}
];
//
// Start the prompt
//
prompt.start();
//
// Get two properties from the user: email, password
//
prompt.get(properties, function (err, result) {
//
// Log the results.
//
console.log('Command-line input received:');
console.log(' name: ' + result.name);
console.log(' password: ' + result.password);
});
Pretty easy right? The output from the above script is:
$ node examples/property-prompt.js
prompt: name: nodejitsu000
error: Invalid input for name
error: Name must be only letters, spaces, or dashes
prompt: name: Nodejitsu Inc
prompt: password:
Command-line input received:
name: Nodejitsu Inc
password: some-password
node-prompt
uses a simple property system for performing a couple of basic validation operations against input received from the command-line. The motivations here were speed and simplicity of implementation to integration of pseudo-standards like JSON-Schema were not feasible.
Lets examine the anatomy of a prompt property:
{
message: 'Enter your password', // Prompt displayed to the user. If not supplied name will be used.
name: 'password' // Key in the JSON object returned from `.get()`.
validator: /^\w+$/ // Regular expression that input must be valid against.
warning: 'Password must be letters' // Warning message to display if validation fails.
hidden: true // If true, characters entered will not be output to console.
default: 'lamepassword' // Default value to use if no value is entered.
empty: false // If false, value entered must be non-empty.
}
Sometimes power users may wish to skip promts and specify all data as command line options.
if a value is set as a property of prompt.override
prompt will use that instead of
prompting the user.
//prompt-everride.js
var prompt = require('prompt'),
optimist = require('optimist')
//
// set the overrides
//
prompt.override = optimist.argv
//
// Start the prompt
//
prompt.start();
//
// Get two properties from the user: username and email
//
prompt.get(['username', 'email'], function (err, result) {
//
// Log the results.
//
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
})
//: node prompt-everride.js --username USER --email EMAIL
A common use-case for prompting users for data from the command-line is to extend or create a configuration object that is passed onto the entry-point method for your CLI tool. node-prompt
exposes a convenience method for doing just this:
var obj = {
password: 'lamepassword',
mindset: 'NY'
}
//
// Log the initial object.
//
console.log('Initial object to be extended:');
console.dir(obj);
//
// Add two properties to the empty object: username and email
//
prompt.addProperties(obj, ['username', 'email'], function (err) {
//
// Log the results.
//
console.log('Updated object received:');
console.dir(obj);
});
Aside from changing property.message
, you can also change prompt.message
and prompt.delimiter
to change the appearance of your prompt.
The basic structure of a prompt is this:
prompt.message + prompt.delimiter + property.message + prompt.delimiter;
The default prompt.message
is "prompt," the default prompt.delimiter
is
": ", and the default property.message
is property.name
.
Changing these allows you to customize the appearance of your prompts! In
addition, node-prompt supports ANSI color codes via the
colors module for custom colors. For a
very colorful example:
var prompt = require("prompt");
//
// The colors module adds color properties to String.prototype
//
require("colors");
//
// Setting these properties customizes the prompt.
//
prompt.message = "Question!".rainbow;
prompt.delimiter = "><".green;
prompt.start();
prompt.get([{ name: "name",
message: "What is your name?".magenta }], function (err, result) {
console.log("You said your name is: ".cyan + result.name.cyan);
});
vows test/*-test.js --spec
FAQs
A beautiful command-line prompt for node.js
The npm package prompt receives a total of 438,766 weekly downloads. As such, prompt popularity was classified as popular.
We found that prompt demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 5 open source maintainers 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
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.