1

I am new to Node.js and I do not understand how the readline module works. Here is my code block:

const { stdout } = require("process");
const {stdin} = require("process");
const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
});


readline.question(`What's your funny name?`, name => {
  console.log(`Hi ${name}!`);
  readline.close();
});

Note that this block of code comes from this location on SO: Node.js "readline" not working as intended

I am expecting that the call to readline.question will pause and wait for the user to respond but this does not happen. The program continues on without pausing for input.

I have also tried

      process.stdin.read()
      process.stdin.on("data", (data) => {
        myAnswers.push(data);
        askQuestions(questionNumber+1);
      })

Again, the code does not pause to allow the user to input some text.

Any assistance would be appreciated.

darlink
  • 69
  • 1
  • 8

1 Answers1

1

This is an example from the official Node.js docs, if you say your code doesn't work, maybe try it this way:

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

Node.js docs: https://nodejs.org/api/readline.html

Bert Van Hecke
  • 211
  • 2
  • 12