'Node.js - promisify readline
As the title states, I was wondering if it is possible to use promisify (https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original) for readline in node.js? I was only able to do it like this:
let data = [];
const parse = () => {
return new Promise((resolve, reject) => {
const rl = readline.createInterface({
input: fs.createReadStream(path)
});
rl.on('line', (line) => {
data.push(line);
});
rl.on('close', () => {
resolve(data);
});
});
};
Solution 1:[1]
Here you have a simple way to do it that doesn't use promisify:
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
function question(query) {
return new Promise(resolve => {
readline.question(query, resolve);
});
}
async function main() {
const name = await question('Whats your name? ');
console.log(`hello ${name}!`);
readline.close();
}
main();
Solution 2:[2]
Here is an example of how I promisify readline.question:
const rl = require('readline');
const { promisify } = require('util');
const readline = rl.createInterface({
input: process.stdin,
output: process.stdout,
});
// Prepare readline.question for promisification
readline.question[promisify.custom] = (question) => {
return new Promise((resolve) => {
readline.question(question, resolve);
});
};
// Usage example:
(async () => {
const answer = await promisify(readline.question)('What is your name? ');
readline.close();
console.log('Hi %s!', answer);
})();
Node (v8) documentation for custom promisified functions: https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_custom_promisified_functions
Solution 3:[3]
try to use bluebird which create http://bluebirdjs.com/docs/api/promise.promisifyall.html
but if the code works. then I think you don't need to promisify that since you already return it as promise.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | romellem |
| Solution 3 | John Michael Villegas |
