{"id":15249,"date":"2024-06-27T15:24:55","date_gmt":"2024-06-27T09:54:55","guid":{"rendered":"https:\/\/codeforgeek.com\/?p=15249"},"modified":"2024-06-27T15:30:18","modified_gmt":"2024-06-27T10:00:18","slug":"nodejs-readline-module","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/nodejs-readline-module\/","title":{"rendered":"Node.js Readline Module: Get User Input From Command Line"},"content":{"rendered":"\n<p>Readline Module is a built-in module in Node.js used for handling user inputs and providing resultant output to the command line. This module offers various methods to help interact with CLI. Using this tool we can create a fully functional CLI-based application. Let&#8217;s learn it in detail.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Introduction to Node.js Readline<\/strong><\/h2>\n\n\n\n<p>The Readline Module is used to interact with the command-line interface (CLI) using which we can read user inputs and write our responses. This module implements the process input stream and output stream to give the functionality of reading input and writing output.&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Example Usage:<\/strong><\/h3>\n\n\n\n<p>Whenever we run &#8220;npm init&#8221; to initialize NPM, it prompts for multiple inputs to create a configuration file package-log.json. The same type of functionality can be achieved using this module.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Get Started with Node.js Readline<\/strong><\/h2>\n\n\n\n<p>The Readline is a built-in package so no need to install it manually. All we have to do is import it into the script we want to use it in.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst readline = require(&#039;readline&#039;);\n<\/pre><\/div>\n\n\n<p>Let&#8217;s check it with real data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Reading and Writing to the Console:<\/strong><\/h3>\n\n\n\n<p>Let&#8217;s write some simple JavaScript code to create a program using the Readline interface to prompt the user for an input <strong>name <\/strong>and then log the message <strong>\u201cHello\u201d<\/strong> concatenated with the entered value.&nbsp;<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst readline = require(&#039;readline&#039;);\n\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.question(&#039;What is your name? &#039;, (name) =&gt; {\n    console.log(&#039;Hello &#039; + name);\n    rl.close();\n});\n<\/pre><\/div>\n\n\n<p>The first line is the importing statement. The next line creates a <strong>readline interface (rl) <\/strong>using the <strong>createInterface <\/strong>method having process <strong>stdin <\/strong>and <strong>stdout <\/strong>as parameters to read and write to the console. Then we invoke the <strong>rl.question() <\/strong>method to emit a message and receive the user input. The callback prints the results to the console and exits <strong>rl<\/strong> interface.<\/p>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"534\" height=\"113\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/Readline-Module-Example.png\" alt=\"Readline Module Example\" class=\"wp-image-15250\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/Readline-Module-Example.png 534w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/Readline-Module-Example-300x63.png 300w\" sizes=\"(max-width: 534px) 100vw, 534px\" \/><\/figure>\n\n\n\n<p><em><em>You can find more information about <\/em><strong><em>process.stdin<\/em><\/strong><em> and <\/em><strong><em>process.stdout<\/em><\/strong><em> in the<\/em><a href=\"https:\/\/codeforgeek.com\/nodejs-process-object-methods\/\"><em> &#8220;Node Process Object&#8221;<\/em><\/a><em> tutorial.<\/em><\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Method of Node.js Readline Module<\/strong><\/h2>\n\n\n\n<p>Let&#8217;s now explore all the methods that the readline module provides to interact with the terminal.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. createInterface()<\/strong><\/h3>\n\n\n\n<p>This method takes process.stdin and process.stdout as arguments to create the instance of the <strong>InterfaceConstructor <\/strong>class. This instance is associated with a single input stream for reading and an output stream for writing.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nreadline.createInterface(input, output);\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst readline = require(&#039;readline&#039;);\n\nconst rl = readline.createInterface(process.stdin, process.stdout);\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong><strong>2. rl.question()<\/strong><\/strong><\/h3>\n\n\n\n<p>This method is used to accept input from the user. This method takes two arguments, a question to ask from the user and a callback function. This callback is used to get the entered value.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nrl.question(message, callback);\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst readline = require(&#039;readline&#039;);\n\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.question(&#039;What is your name? &#039;, (name) =&gt; {\n    console.log(&#039;Hello &#039; + name);\n});\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"538\" height=\"109\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.question-Example-Output.png\" alt=\"rl.question Example Output\" class=\"wp-image-15251\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.question-Example-Output.png 538w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.question-Example-Output-300x61.png 300w\" sizes=\"(max-width: 538px) 100vw, 538px\" \/><\/figure>\n\n\n\n<p>In the output, you can notice that the application keeps asking for input even after entering an input, for getting rid of this we have another method<strong> rl.close()<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong><strong>3. rl.close()<\/strong><\/strong><\/h3>\n\n\n\n<p>This method is used to close the Interface i.e. take control of the input and output stream from the instance of InterfaceConstructor.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nrl.close()\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst readline = require(&#039;readline&#039;);\n\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.question(&#039;What is your name? &#039;, (name) =&gt; {\n    console.log(&#039;Hello &#039; + name);\n    rl.close();\n});\n\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"536\" height=\"114\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.close-Example-Output.png\" alt=\"rl.close Example Output\" class=\"wp-image-15252\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.close-Example-Output.png 536w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.close-Example-Output-300x64.png 300w\" sizes=\"(max-width: 536px) 100vw, 536px\" \/><\/figure>\n\n\n\n<p>This method does not immediately stop the other events from happening like \u2018line\u2019, \u2018close\u2019, \u2018resume\u2019, etc.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong><strong>4. rl.resume()<\/strong><\/strong><\/h3>\n\n\n\n<p>This method resumes the input streams if it is paused but it doesn&#8217;t prompt anything.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nrl.resume()\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst readline = require(&#039;readline&#039;);\n\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.question(&#039;What is your name? &#039;, (name) =&gt; {\n    console.log(&#039;Hello &#039; + name);\n    rl.close();\n    rl.resume();\n});\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"538\" height=\"109\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.question-Example-Output-1.png\" alt=\"rl.question Example Output\" class=\"wp-image-15253\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.question-Example-Output-1.png 538w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.question-Example-Output-1-300x61.png 300w\" sizes=\"(max-width: 538px) 100vw, 538px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong><strong>5. rl.setPrompt()<\/strong><\/strong><\/h3>\n\n\n\n<p>This method is used to set prompts. It takes a string containing any kind of message as an argument.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nrl.setPrompt(message)\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst readline = require(&#039;readline&#039;);\n\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt(&#039;Enter your name: &#039;);\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong><strong>6. rl.prompt()<\/strong><\/strong><\/h3>\n\n\n\n<p>This method is used to output the value set by <strong>rl.setPrompt()<\/strong> in the new line in the console. It resumes the input stream if it is paused and provides a new location for the user to enter the input.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nrl.prompt()\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst readline = require(&#039;readline&#039;);\n\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt(&#039;Enter your name: &#039;);\n\nrl.prompt();\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"537\" height=\"89\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.prompt-Example-Output.png\" alt=\"rl.prompt Example Output\" class=\"wp-image-15254\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.prompt-Example-Output.png 537w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.prompt-Example-Output-300x50.png 300w\" sizes=\"(max-width: 537px) 100vw, 537px\" \/><\/figure>\n\n\n\n<p>To get the entered input, we have to use another method<strong> rl.on()<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>7. rl.on()<\/strong><\/h3>\n\n\n\n<p>This method takes an event and a callback. The event can be <strong>\u201cline\u201d <\/strong>which will activate when the enter key is pressed,<strong> \u201cpause\u201d<\/strong> which is active when input steam is paused, <strong>\u201cresume\u201d<\/strong> when it resumes, <strong>\u201cSIGINT\u201d <\/strong>when the user presses ctrl + c, and <strong>\u201cSIGTSTP\u201d<\/strong> when the user presses ctrl + z.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nrl.on(event, callback)\n<\/pre><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst readline = require(&#039;readline&#039;);\n\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt(&#039;Enter your name: &#039;);\n\nrl.prompt();\n\nrl.on(&#039;line&#039;, (line) =&gt; {\n  console.log(`Hello ${line}`);\n  rl.close();\n});\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"538\" height=\"115\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.on-Example-Output.png\" alt=\"rl.on Example Output\" class=\"wp-image-15255\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.on-Example-Output.png 538w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2022\/12\/rl.on-Example-Output-300x64.png 300w\" sizes=\"(max-width: 538px) 100vw, 538px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Creating a CLI-Based Calculator App Using Node.js Readline Module<\/strong><\/h2>\n\n\n\n<p>Let&#8217;s create a calculator app using the methods we just learned.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nconst readline = require(&#039;readline&#039;);\n\nconst rl = readline.createInterface({\n    input: process.stdin,\n    output: process.stdout\n});\n\nconst calculate = (num1, num2, operator) =&gt; {\n    switch (operator) {\n        case &#039;+&#039;:\n            return num1 + num2;\n        case &#039;-&#039;:\n            return num1 - num2;\n        case &#039;*&#039;:\n            return num1 * num2;\n        case &#039;\/&#039;:\n            return num1 \/ num2;\n        default:\n            return null;\n    }\n};\n\nrl.question(&#039;Enter the first number: &#039;, (firstNumber) =&gt; {\n    const num1 = parseFloat(firstNumber);\n    rl.question(&#039;Enter the second number: &#039;, (secondNumber) =&gt; {\n        const num2 = parseFloat(secondNumber);\n        rl.question(&#039;Enter the operator (+, -, *, \/): &#039;, (operator) =&gt; {\n            const result = calculate(num1, num2, operator);\n            if (result !== null) {\n                console.log(`${num1} ${operator} ${num2} = ${result}`);\n            } else {\n                console.log(&#039;Invalid operation!&#039;);\n            }\n            rl.close();\n        });\n    });\n});\n<\/pre><\/div>\n\n\n<p>Here we have created a function that takes two numbers and one operator, then used a switch case to perform the operation based on the operator and returned the result.<\/p>\n\n\n\n<p>Then we used the methods that we learned to prompt the user for the number input and then pass it to our function. Additionally, we use a conditional statement to make sure that an error message is displayed if the result is null.<\/p>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"670\" height=\"117\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/06\/Final-Output.png\" alt=\"Final Output\" class=\"wp-image-31014\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/06\/Final-Output.png 670w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/06\/Final-Output-300x52.png 300w\" sizes=\"(max-width: 670px) 100vw, 670px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Summary<\/strong><\/h2>\n\n\n\n<p>In short, the nodejs readline module is used for reading input and writing output to the console. Using it one can prompt different types of messages in the command line while giving the option to add the input, making it ideal for interacting with the CLI.<\/p>\n\n\n\n<p><em><strong>Read More:<\/strong><\/em><a href=\"https:\/\/codeforgeek.com\/asynchronous-programming-in-node-js\/\"><strong><em> Asynchronous Programming in Node.js &#8211; Callback, Promises &amp; Async Await<\/em><\/strong><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Reference<\/strong><\/h2>\n\n\n\n<p><a href=\"https:\/\/nodejs.org\/api\/readline.html\" target=\"_blank\" rel=\"noopener\">https:\/\/nodejs.org\/api\/readline.html<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Readline Module is a built-in module in Node.js used for handling user inputs and providing resultant output to the command line. This module offers various methods to help interact with CLI. Using this tool we can create a fully functional CLI-based application. Let&#8217;s learn it in detail. Introduction to Node.js Readline The Readline Module is [&hellip;]<\/p>\n","protected":false},"author":79,"featured_media":29686,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[14],"tags":[],"class_list":["post-15249","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-nodejs"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Node.js-Readline-Module.png",1280,720,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Node.js-Readline-Module-150x150.png",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Node.js-Readline-Module-300x169.png",300,169,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Node.js-Readline-Module-768x432.png",768,432,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Node.js-Readline-Module-1024x576.png",1024,576,true],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Node.js-Readline-Module.png",1280,720,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Node.js-Readline-Module.png",1280,720,false]},"uagb_author_info":{"display_name":"Aditya Gupta","author_link":"https:\/\/codeforgeek.com\/author\/aditya\/"},"uagb_comment_info":0,"uagb_excerpt":"Readline Module is a built-in module in Node.js used for handling user inputs and providing resultant output to the command line. This module offers various methods to help interact with CLI. Using this tool we can create a fully functional CLI-based application. Let&#8217;s learn it in detail. Introduction to Node.js Readline The Readline Module is&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/15249","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/79"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=15249"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/15249\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/29686"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=15249"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=15249"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=15249"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}