1

I'm trying to get unprompted input from the user in a NodeJS server. The reason is that I want to be able to send strings that can be interpreted as commands while a server is running such as commands to flush the cache.

Now, originally, I used readline as follows:

import * as ReadLine from 'readline';

export default function InitTerminal() {
    const terminal = ReadLine.createInterface({
        input: process.stdin,
        terminal: false
    });

    terminal.on('line', (input) => {
        console.log(input);
        switch(input.toString()) {
            default:
                console.log('Unknown Command');
                break;
        }
    });
}

The issue was that after most inputs, I would get:

rl.on line * input *

Where * input * refers to the string representation of the buffer input from process.stdin. The weird thing is, the on line triggers only occassionaly and typically I will get that line and my listener doesn't trigger. The same thing happens when I don't use ReadLine and just add a listener to process.stdin. Something is triggering node to print out the output above. I'm using node 11.12.0 and ts-node-dev for typescript in development mode.

So what I'm asking is how can I use node to get unprompted input as commands? Either by modifying my original code or any way I haven't thought of.

Kind thanks.

1 Answer 1

1

The problem was that ts-node-dev plays with the stdin. That means it's hard to get the stdin while using it. What I hade to do was create an npm script called build:dev which compiled my typescript and then ran it. Then I could use the process.stdin without concern.

A way to possible watch changes while doing this is to use nodemon instead of ts-node-dev and just compile the typescript when needed

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.