How to prevent readline in Node from exiting on line event?

twitter logo github logo ・1 min read

I'm working on a command line tool using Node and I'd like to prevent it from exiting when using the readline module when the user inputs the "Return" key or something that indicates a new line. I saw that readline has an event handler for line but can't figure out how to prevent it from exiting. Meaning I'd like to allow for the user to be able to use the return and it adds a carriage return to the input for readline instead of exiting it.

I'd like to exit readline only when the user uses control-C or control-D.

twitter logo DISCUSS (4)
markdown guide

It sounds like you want something like this?

const readline = require('readline');

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

rl.prompt("Want to add some newlines?")

rl.on('line', (input) => {
  console.log(`Received: ${input}`);

rl.on('SIGINT', () => {
    rl.question('Are you sure you want to exit? ', (answer) => {
      if (answer.match(/^y(es)?$/i)) rl.pause();

Si! Thanks so much for helping with your answer! I was able to solve my problem based on your solution. Is SIGINT what is triggered by default when a new line event occurs? So handling the SIGINT event did the trick?


No worries mate - glad it was helpful. I've never actually used readline, so it was a good opportunity to give it a spin 😁.

SIGINT is the interrupt signal. The terminal sends it to the foreground process when the user presses ctrl-c. We handle this signal so we can gracefully shut down rl (rl.pause()).

line is the event that is triggered when a new line occurs. I would assume that the default behaviour of a new line is to call rl.pause() but we're capturing the event instead and doing our own thing.

Classic DEV Post from May 1 '19

Build a 💣 Bomb-Diggity Technical Presentation (🎤 Mic Drop Optional)

The steps and process behind building a great technical presentation.

Michael Lee 🍕 profile image
Maker of things, giver of high-fives 🖐