Node.js multiline input
Asked Answered
H

2

16

I'd like to prompt the user for input, let the user enter multiple lines of text, hitting enter between each line, then terminate the input by pressing CTRL+D or some such thing.

With "keypress", I can catch the EOF, but I would have to handle all the echoing, backspace handling, terminal escape sequences, etc. manually. It would be much better if I could use "readline", but somehow intercept the CTRL+D (EOF) with "keypress", but I'm not sure how I would go about that.

Hadleigh answered 13/10, 2014 at 23:1 Comment(0)
O
21

You can use the line and close events:

var readline = require('readline');

var input = [];

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

rl.prompt();

rl.on('line', function (cmd) {

    input.push(cmd);
});

rl.on('close', function (cmd) {

    console.log(input.join('\n'));
    process.exit(0);
});
Orifice answered 13/10, 2014 at 23:18 Comment(1)
Commands such as git also open a default editor for user input. Is this also possible with Node?Huynh
B
2

The @inquirer/editor package does a great job this

It opens the user's default editor for input

For example

import editor from '@inquirer/editor';

const story = await editor({
  message: "Tell me a story",
  waitForUseInput: true,
  postfix: '.md',
})

https://www.npmjs.com/package/@inquirer/editor

Bracelet answered 23/9, 2023 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.