Tuesday 25 April 2017

How to read (redirected) stdin line by line?

Hi there. I'm trying to use JS (Node) in some coding contests to get a better feel of the language. The problem is, judge systems are checking the code by redirecting stdin and stdout. Right now I do it this way:let text = ''; process.stdin.setEncoding('utf-8'); process.stdin.on('readable', () => { let data = process.stdin.read(); if (data !== null) { text += data; } }); process.stdin.on('end', () => { console.log(solveStuff(text)); }); It works, but it eats a lot of memory since all the input is stored and not processed line by line. I found out Readline and I'm trying to do it this way:const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); rl.question('', (line) => { let [a, b] = line.split(' ').map(Number); console.log(a + b); process.exit(); }); The problem is, it only works in the interactive console. The moment I redirect a file to stdin, the output disappears completely. I suppose I'm doing something wrong here, but hours of googling brought me nothing. Any help, please?

Submitted April 25, 2017 at 01:09PM by Rinnve

No comments:

Post a Comment