Search code examples
node.jscommand-linecommand-line-interfaceblocking

Blocking method of waiting for input and outputting


I'm writing a messaging app in node for the command line. It needs be able to print newly received messages while allowing the user to type a message to send whenever they want.

Can you help me figure out how to create a blocking method that exits after receiving a specific input like "EXIT", but allows printing to the console and can receive and handle input that doesn't match the exit case? Thanks in advance.


Solution

  • You can't do that in node.js. If you want to receive other types of events, you can't be blocking the main JS thread. Javascript in node.js is single threaded and event driven. The only way to get the next event is to be non-blocking so the main JS thread can fetch the next event in the event queue.

    You can very likely deliver the desired functionality you want with non-blocking I/O. You would have to show us the code you have so far for us to give you further advice on how to accomplish that with the code you have.

    Keep in mind that you can exit a node.js process at any time with process.exit() so you could just have asynchronous, event driven input handler and whenever it found specific input like EXIT, it would then call process.exit() to exit the process. For other input, it would dispatch to the appropriate handler based on what was typed.