Created
October 29, 2017 15:58
-
-
Save tinovyatkin/4316e302d8419186fe3c6af3f26badff to your computer and use it in GitHub Desktop.
`util.promisify` for `readline.question`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); | |
})(); | |
*/ |
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);
I really doubt this code could run. You're reassigning a const. And doing many other strange things. Did you just copy-paste random code?
I really doubt this code could run. You're reassigning a const. And doing many other strange things. Did you just copy-paste random code?
The base idea works, it was just untested, so heres the tested version:
const { promisify } = require('util');
const readline = require("readline");
let rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question[promisify.custom] = (question) => {
return new Promise((resolve) => {
rl.question(question, resolve);
});
};
rl.questionSync = promisify(rl.question);
runAsync();
async function runAsync() {
let ans = await rl.questionSync("What is your name ?\n");
console.log(ans);
}
Wow, that's a collection of antipatterns. Anyway, promisified version is landed in Node 16
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the code! I found another to do the same thing, I thought I'd share: