1

How to make the code below work with await?

var readline = require('readline');
var Writable = require('stream').Writable;

var mutableStdout = new Writable({
  write: function(chunk, encoding, callback) {
    if (!this.muted)
      process.stdout.write(chunk, encoding);
    callback();
  }
});

mutableStdout.muted = false;

var rl = readline.createInterface({
  input: process.stdin,
  output: mutableStdout,
  terminal: true
});

//add await
rl.question('Amount: ', function(password) {
  console.log('\nAmount is ' + password);
  rl.close();
});

//add await
rl.question('Secret: ', function(password) {
  console.log('\nSecret is ' + password);
  rl.close();
});

mutableStdout.muted = true;

Secret should be queried with mutableStdout.muted set to true, and Amount should be queried with mutableStdout.muted set to false.

The both values should be saved to the variables amount and secret.

The code should work from the console with

node mycode.js
Alexey Starinsky
  • 3,699
  • 3
  • 21
  • 57
  • 1
    Don't pass a callback when you want to use promises. Also read [the documentation](https://nodejs.org/api/readline.html#rlquestionquery-options) – Bergi Mar 21 '23 at 20:52

1 Answers1

1

node:readline provides a sub-module called node:readline/promises using a promise-based API.

Import this API instead with require("node:readline/promises") or ESM import from that same module. You can then await rl.question("...") with your desired text.

The docs show this example:

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

const rl = readline.createInterface({ input, output });

const answer = await rl.question('What do you think of Node.js? ');

console.log(`Thank you for your valuable feedback: ${answer}`);

rl.close();
0xLogN
  • 3,289
  • 1
  • 14
  • 35