uglycode
uglycode

Reputation: 3082

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);
        });
    });
};

Upvotes: 12

Views: 5349

Answers (4)

fregante
fregante

Reputation: 31698

Starting in Node 17, it's already promisified:

import { stdin, stdout } from 'node:process';
import * as readline from 'node:readline/promises';

const rl = readline.createInterface({ input: stdin, output: stdout });
const answer = await rl.question('What is your name? ');
console.log('Thank you', answer);
rl.close();

See the documentation:

Upvotes: 0

Jesús López
Jesús López

Reputation: 9221

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();

Upvotes: 17

Josef Engelfrost
Josef Engelfrost

Reputation: 2965

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

Upvotes: 7

John Michael Villegas
John Michael Villegas

Reputation: 336

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.

Upvotes: 0

Related Questions