readline, timers & scheduling in nodejs

medium · Node.js — Server-side JavaScript

The readline module in Node.js provides an interface for reading data from a Readable Stream (like process.stdin ) one line at a time. It is the go-to tool for creating Command Line Interface (CLI) tools that require user input. 1. Basic Setup To use it, you create an interface by connecting an input stream (where the user types) and an output stream (where the prompt is displayed). const readline = require('readline'); const rl = readline.createInterface({   input: process.stdin,   output: process.stdout }); 2. Key Methods A. rl.question() This is the most common method. It displays a prompt, waits for user input, and then executes a callback with the answer. rl.question('What is your name? ', (answer) => {   console.log(`Hello, ${answer}!`);   rl.close(); // Crucial: You must close the interface or the process won't exit }); B. rl.setPrompt() and rl.prompt() Used to create more interactive, shell-like experiences. rl.setPrompt('Careeroza-CLI> '); rl.prompt(); rl.on('line', (line) => {   if (line.trim() === 'exit') rl.close();   console.log(`You typed: ${line}`);   rl.prompt(); }); 3. Using Readline with Promises (Modern) The callback style can become messy (callback hell). In modern Node.js, you can use the promises version of the API for much cleaner code using async/await . const readline = require('readline/promises'); async function askQuestion() {   const rl = readline.createInterface({     input: process.stdin,     output: process.stdout   });   const name = await rl.question('Enter your username: ');   const password = await rl.question('Enter your password: ');   console.log(`Logged in as ${name}`);   rl.close(); } askQuestion(); 4. The line Event The line event is triggered whenever the input stream receives an end-of-line input ( \n , \r , or \r\n ). This is perfect for reading large text files line-by-line without loading them entirely into memory. const fs = require('fs'); const rl = readline.createInterface({   input: fs.createReadStream('server-logs.txt'),   crlfDelay: Infinity // Treats \r\n as a single line break }); rl.on('line', (line) => {   if (line.includes('ERROR')) {     console.log('Found an error in logs:', line);   } }); 5. Why not just use process.stdin.on('data') ? While you can read raw data from stdin , readline offers several high-level advantages: Buffer Handling: It automatically handles the buffering of characters until a new line is reached. Tab Completion: It supports adding custom tab-completion for your CLI. History: It can remember previous inputs (allowing users to use the Up/Down arrows). ANSI Support: It handles terminal cursor movements and colors more gracefully.

Back to Node.js — Server-side JavaScript

Browse all study material on Careeroza