Warm tip: This article is reproduced from serverfault.com, please click

Node.js readline module: stop reprinting the line just read

发布于 2020-12-03 06:07:06

I'm using the readline module in Node (12) to accept user input as such:

import * as readline from "readline";

process.stdin.setEncoding('utf-8');
console.log("input is a TTY?",process.stdin.isTTY);

const rl = readline.createInterface({input: process.stdin, output: process.stdout, prompt: '> '});
rl.prompt();
rl.on('line' ,inputLine => { inputStringLines.push(inputLine); rl.prompt(); });
rl.on('close',() => { console.log('input has closed'); main(); });

The lines are correctly captured into my inputStringLines array but annoyingly, the process is printing out every line just read:

enter image description here

How can I get rid of the extra lines (the ones without the > prompt)

Questioner
BeetleJuice
Viewed
0
BeetleJuice 2020-12-04 03:11:57

I fixed it by changing how run my script. Before, I used nodemon with node's -r ts-node/register option. The issue went away when I switched to using ts-node-dev to execute the script.

Note also that process.stdin.isTTY is now correctly set whereas it was undefined before (look at the first line in the image below, vs in the original post)

enter image description here

Still don't know the root cause, but I'm happy to move on.