Zed Evans
Zed Evans

Reputation: 136

Best way to write into the process.stdin in node.js and parse the line?

I'm proggraming in the MEAN stack , so I have my app.js and I want to build a process which will take commands from the shell its running on (process.stdin)
Currently I have tried :

const readline = require('readline');

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

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  console.log(`Thank you for your valuable feedback: ${answer}`);

  rl.close();
});

but it writes my input twice and exit after 1 line .
I need a readline function that will loop and take infinite commands from me .
How can I get it ?

Upvotes: 1

Views: 654

Answers (1)

rsp
rsp

Reputation: 111316

It exits because of:

rl.close();

If you want to read line by line interactively using readline:

rl.on('line', (line) => {
  // use line here
});

Another way that may be convenient for less interactive workflows but still works for interactive:

const filt = require('filt');
filt((line) => {
  // use line here
});

The second example uses the filt module (disclaimer: I'm the author of that module).

Upvotes: 1

Related Questions