stdio
Version:
Standard input/output manager for Node.js
68 lines (67 loc) • 2.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const DEFAULT_MAX_RETRIES = 3;
function getInputStream(config) {
return config.inputStream || process.stdin;
}
function isInArrBounds(arr, index) {
return arr !== undefined && Number.isInteger(index) && index >= 0 && index < arr.length;
}
function print(text, config) {
const inputStream = getInputStream(config);
if (inputStream !== process.stdin)
return;
const { options, defaultIndex } = config;
if (options) {
if (isInArrBounds(options, defaultIndex))
text += ' (default ' + options[defaultIndex] + ')';
text += ' [' + options.join('/') + ']';
}
text += ': ';
process.stdout.write(text);
}
function getOnError(question, config, callback) {
const inputStream = getInputStream(config);
return (listener, tries) => {
if (inputStream === process.stdin)
console.log('Unexpected answer. %d retries left.', tries);
if (!tries) {
inputStream.removeListener('data', listener);
inputStream.pause();
callback('Retries spent');
}
else {
print(question, config);
}
};
}
function getListener(question, config, callback) {
const inputStream = getInputStream(config);
let tries = config.maxRetries || DEFAULT_MAX_RETRIES;
const onError = getOnError(question, config, callback);
function listener(data) {
let answer = data.toString().trim();
if (config.options && !config.options.includes(answer)) {
if (isInArrBounds(config.options, config.defaultIndex) && answer === '') {
answer = config.options[config.defaultIndex].toString().trim();
}
else
return onError(listener, --tries);
}
inputStream.removeListener('data', listener);
inputStream.pause();
callback('', answer);
}
return listener;
}
function ask(question, config = {}) {
return new Promise((resolve, reject) => {
const callback = (error, value) => (error ? reject(new Error(error)) : resolve(value !== null && value !== void 0 ? value : ''));
const inputStream = getInputStream(config);
inputStream.resume();
const listener = getListener(question, config, callback);
inputStream.addListener('data', listener);
print(question, config);
});
}
exports.default = ask;