cloudapp-dl
Version:
CloudApp/Zight API client and CLI. Use as a CLI tool to download videos or as a programmatic library to interact with the Zight API.
108 lines (94 loc) • 2.57 kB
JavaScript
import readline from 'readline';
/**
* Create a readline interface
* @returns {Object} - Readline interface
*/
const createInterface = () => {
return readline.createInterface({
input: process.stdin,
output: process.stdout
});
};
/**
* Prompt user for input
* @param {string} question - The question to ask
* @returns {Promise<string>} - User's response
*/
export const prompt = (question) => {
return new Promise((resolve) => {
const rl = createInterface();
rl.question(question, (answer) => {
rl.close();
resolve(answer);
});
});
};
/**
* Prompt user for password (hidden input)
* @param {string} question - The question to ask
* @returns {Promise<string>} - User's password
*/
export const promptPassword = (question) => {
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Mute output after question is displayed
process.stdout.write(question);
const stdin = process.stdin;
const wasRaw = stdin.isRaw;
if (stdin.isTTY) {
stdin.setRawMode(true);
}
let password = '';
const onData = (char) => {
char = char.toString();
switch (char) {
case '\n':
case '\r':
case '\u0004': // Ctrl-D
if (stdin.isTTY) {
stdin.setRawMode(wasRaw);
}
stdin.removeListener('data', onData);
rl.close();
console.log(); // New line after password
resolve(password);
break;
case '\u0003': // Ctrl-C
if (stdin.isTTY) {
stdin.setRawMode(wasRaw);
}
stdin.removeListener('data', onData);
rl.close();
process.exit(1);
break;
case '\u007F': // Backspace
password = password.slice(0, -1);
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write(question + '*'.repeat(password.length));
break;
default:
password += char;
process.stdout.write('*');
}
};
stdin.on('data', onData);
});
};
/**
* Prompt for confirmation
* @param {string} question - The question to ask
* @returns {Promise<boolean>} - True if confirmed
*/
export const confirm = async (question) => {
const answer = await prompt(`${question} (y/n): `);
return answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes';
};
export default {
prompt,
promptPassword,
confirm
};