This will call abort after 5 seconds of inactivity, given signal is used on line 19 in the rl.question.
On line 8 we define a timeout of 5 seconds and attached it to ac.abort() call with a setTimeout. Next up, in line 4 we use the signal variable which is part of the native Abort controller. This fits our use-case well, as we are trying to stop the script if the user is not able to answer within 5 seconds. The Abort Controller as per the official documentation is “A utility class used to signal cancelation in selected promise-based APIs”. On line 3 we instantiate the Abort Controller. The main changes in this example which adds another layer of timeout feature on the above basic example of Node.js readline are as follows. const readline = require ( 'readline/promises' ) Ĭonst seconds.
#Nodejs readline code#
Below is the code basic example of Node.js readline native module with promises, async-await, and process module. The example is very simple it asks the user the value of 4x4 if the user enters 16 it says it is correct else it says it is incorrect and try again. Given Node 17 is the currently active version and Node 18 will be the latest LTS from mid-Apr 2022, this should be a relevant example apt with the present time and very useful in the future too. This simple example will use the latest readline/promises native package only available from Node 17 and above. Basic example of Node.js readline #īefore we go into an example of Node.js readline with more things, we will first look into a basic example. Given that we have mentioned the required things, in the next section we will start diving into the code.
This tutorial will only use a native module with Common JS (CJS) so NPM knowledge is optional.
You will need Node.js v17+ working on your machine and basic knowledge of Node.js would be helpful.
#Nodejs readline how to#
Below are the prerequisites for this tutorial on how to create a simple Node.js CLI app using readline native module: For smaller CLI apps that don’t need external NPM dependencies Node.js Readline module would suffice. If you want to build on a full-on CLI application it might be better to use something like Oclif or commander.js. In this post, we will learn how to create a basic Node.js CLI app using the latest Readline on Node 17 with promises and async/await. With the Node.js Readline native module, we can create CLI apps. Node.js can be used for multiple purposes, creating a Command Line Interface (CLI) app is one of them.