简体   繁体   中英

Reading multiple lines in node.js

I am currently doing some tests at Kattis to practice my node.js skills but I'm stuck with this one .

Below is my code:

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
  
rl.on("line", (line) => {
  let inputData = line.split("/n");
  console.log(inputData[0].length);

  // result = (inputData[0].length) >= (inputData[1].length) ? 'go' : 'no';
  // console.log(result)
});

..and in the console log inputData[0].length, I am getting:

4
6

When I used inputData[1] , it gives me undefined. How can I compare these 2 lines so 'go' or 'no' will be displayed as the result?

By definition, you get ONE line at a time with this interface. The line event in the readline interface just gives you one line at a time. So, it will never give you two lines you can compare.

If you just want to see compare successive lines in the file with whatever logic you want, you can keep the previous line in a higher scoped variable and compare the next line to that when the next line event occurs.

const readline = require("readline");

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

let previousLine = "";
  
rl.on("line", (line) => {
    if (!previousLine) {
        // no previous line to compare to, so just remember this line
        previousLine = line;
    } else {
        let result = previousLine.length >= line.length ? 'go' : 'no';
        console.log(result);
        previousLine = line;
    }
});

But, as I've said in my comments a couple of times, if you tell us what actual problem you're trying to solve or what you're really trying to accomplish, then we can likely help you with a good solution to the real problem.

Here's a couple of simple solutions to this problem to help illustrate readline management in Kattis, which can be a bit tricky to get the hang of:

Using .on("close", ...) :

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
  
const lines = [];
rl.on("line", line => lines.push(line))
  .on("close", () =>
    console.log(lines[0].length < lines[1].length ? "no" : "go")
  )
;

Using .once("line", ...) :

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
  
rl.once("line", line1 =>
  rl.once("line", line2 =>
    console.log(line1.length < line2.length ? "no" : "go")
  )
);

See also Getting input in Kattis challenges - readline js for more complex cases where you need to read n lines or until EOF to solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM