0

I'm having a hard time undestanding how to use the readline library from NodeJS to read two different strings for a Kattis challenge.

See, in their documentation there's the following example:

const readline = require('readline');

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

rl.on('line', (line) => {
    var nums = line.split(' ');
    var a = parseInt(nums[0]);
    var b = parseInt(nums[1]);
    /*Solve the test case and output the answer*/
});

I need to read two strings and then manipulate them. I've already tried doing:

const readline = require('readline');

var string1 = '';
var string2 = '';

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

rl.on('line', (line) => {
    var string1 = line;
});

rl.on('line', (line) => {
    var string2 = line;
});

//manipulating strings...

and even:

const readline = require('readline');

var string1 = '';
var string2 = '';

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

rl.question('', (answer) => {
    var string1 = answer;
});

rl.question('', (line) => {
    var string2 = answer;
});

//manipulating strings...

But I keep getting a Run time error. What am I doing wrong, exactly?

Daniel Bertoldi
  • 359
  • 4
  • 14
  • 2
    You're getting a runtime error because you're assigning a variable in an asynchronous scope (in the callback for `rl.on('line',..` or `rl.question(..`) and trying to access it later synchronously. I'd recommend reading up on asynchronous JavaScript before proceeding with this challenge, or any JS scripting that might involve it. – Klaycon Nov 12 '19 at 19:46
  • 2
    Additionally, although it doesn't produce an error, it is very bad style and reduces readability to re-declare variables using `var` like you do in `var string1 = answer;` - at first I thought you were declaring a variable in one scope and trying to use it in another. – Klaycon Nov 12 '19 at 19:47
  • What challenge are you doing? Many possible dupes here explaining how to read lines in JS for Kattis: [1](https://stackoverflow.com/a/69559880/6243352), [2](https://stackoverflow.com/a/69562323/6243352), [3](https://stackoverflow.com/a/72549523/6243352), [4](https://stackoverflow.com/a/69562068/6243352), [5](https://stackoverflow.com/a/69562205/6243352) – ggorlen Sep 23 '22 at 02:09

0 Answers0