Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        });
    });
};
like image 798
uglycode Avatar asked Oct 24 '17 10:10

uglycode


People also ask

What does Promisify do in node JS?

promisify() method basically takes a function as an input that follows the common Node. js callback style, i.e., with a (err, value) and returns a version of the same that returns a promise instead of a callback.

How do I read a file line by line in node?

Method 1: Using the Readline Module: Readline is a native module of Node. js, it was developed specifically for reading the content line by line from any readable stream. It can be used to read data from the command line. const readline = require('readline');

What is readline in node JS?

Readline Module in Node.js allows the reading of input stream line by line. This module wraps up the process standard output and process standard input objects. Readline module makes it easier for input and reading the output given by the user.


1 Answers

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();
like image 180
Jesús López Avatar answered Sep 23 '22 20:09

Jesús López