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);
});
});
};
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.
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');
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With