Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
`util.promisify` for `readline.question`
'use strict';
// Promisifies readline.question function using node native `util.promisify`
// readline.question takes one callback that returns the answer, so it need custom promisifying
const readline = require('readline');
const { promisify } = require('util');
readline.Interface.prototype.question[promisify.custom] = function(prompt) {
return new Promise(resolve =>
readline.Interface.prototype.question.call(this, prompt, resolve),
);
};
readline.Interface.prototype.questionAsync = promisify(
readline.Interface.prototype.question,
);
/* Usage example then:
(async () => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const airportCode = await rl.questionAsync(
'Enter the airport code for stats: ',
);
rl.close();
console.info('Getting stats for %s...', airportCode);
})();
*/
@engelfrost

This comment has been minimized.

Copy link

@engelfrost engelfrost commented Feb 19, 2019

Thanks for the code! I found another to do the same thing, I thought I'd share:

const readline = require('readline');
const { promisify } = require('util');
const readline = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    });

// Prepare readline.question for promisification
readline.question[util.promisify.custom] = (question) => {
  return new Promise((resolve) => {
    readline.question(question, resolve);
  });
};

// Usage example:
const answer = await promisify(readline.question)('What is your name? ');
readline.close();
console.log('Hi %s!', answer);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.