Search code examples
javascriptnode.jsasync-awaitreadline

Issue with readline module in node


enter image description hereI have been trying to solve DSA problems using JS. So the issue I faced initially was taking user input. So went and searched and got that I can use readline module to do the same. So created an Interface and tried getting user Input, but it seem to be stuck after taking the user Input. Unable to figure out whats wrong, not getting any error as well.

/* Given an array and Q queries, where a query looks like the following,
(l,r)--> l,r are the indices of the array. For each query, you need to find the sum between the given indices
*/
import { getUserInput } from "../index.js";

async function preCompute() {
  let arraySize = 0;
  // get the number for user inputs
  arraySize = await getUserInput("Enter the array size : ");
  console.log("ARRAY SIZE", arraySize);
  const userInputs = [];
  for (let i = 0; i < Number(arraySize.trim()); i++) {
    const currentUserInput = await getUserInput("Enter the number");
    userInputs.push(Number(currentUserInput.trim()));
  }
  const prefixSumArray = [];
  for (let i = 0; i < arraySize; i++) {
    if (i === 0) {
      prefixSumArray[i] = userInputs[i];
    } else {
      prefixSumArray[i] = prefixSumArray[i - 1] + userInputs[i];
    }
  }
  let Q = 0;
  Q = await getUserInput("Enter the number of queries i.e Q");
  for (let i = 0; i < Q; i++) {
    const queryInput = await getUserInput(
      "Enter space separated value for l and r"
    );
    const [l, r] = queryInput.split(" ");
    console.log(
      `Sum between l and r: ${
        l !== 0 ? prefixSumArray[r] - prefixSumArray[l - 1] : prefixSumArray[r]
      }`
    );
  }
}

preCompute();

and my index.js looks something like this:

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

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

export const getUserInput = (prompt) => {
  return new Promise((resolve) => {
    rl.question(prompt, (answer) => {
      console.log("Running callback to resolve");
      resolve(answer);
    });
  });
};

Would be great if some could point out what's wrong.


Solution

  • You are using the promise API of readline, so you should not pass a callback argument to rl.question. That method returns a promise. Your getUserInput could therefore just be this:

    export const getUserInput = (prompt) => rl.question(prompt);
    

    Secondly, once you're done, you should close the interface with the I/O streams. This could be done as the final statement in preCompute:

    rl.close();