typescriptbeginner
Interactive CLI with Readline
Build interactive command-line interfaces using Node.js readline with prompts, history, and auto-completion.
typescriptPress ⌘/Ctrl + Shift + C to copy
import * as readline from 'readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
completer: (line: string) => {
const commands = ['help', 'list', 'add', 'remove', 'quit'];
const hits = commands.filter(c => c.startsWith(line));
return [hits.length ? hits : commands, line];
},
});
const items: string[] = [];
function prompt() {
rl.question('> ', (input) => {
const [cmd, ...args] = input.trim().split(' ');
switch (cmd) {
case 'add':
const item = args.join(' ');
if (item) { items.push(item); console.log(`Added: ${item}`); }
else console.log('Usage: add <item>');
break;
case 'list':
if (items.length === 0) console.log('No items');
else items.forEach((item, i) => console.log(` ${i + 1}. ${item}`));
break;
case 'remove':
const idx = parseInt(args[0]) - 1;
if (idx >= 0 && idx < items.length) {
const removed = items.splice(idx, 1);
console.log(`Removed: ${removed[0]}`);
} else console.log('Invalid index');
break;
case 'help':
console.log('Commands: add, list, remove, help, quit');
break;
case 'quit':
rl.close();
return;
default:
console.log(`Unknown command: ${cmd}. Type 'help'`);
}
prompt();
});
}
console.log('Interactive CLI — type help for commands');
prompt();Use Cases
- Building simple CLI tools
- Interactive data entry
- Terminal-based task managers
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
Node.js Worker Threads for Parallel Processing
Use Worker Threads to run CPU-intensive tasks in parallel without blocking the event loop.
Best for: CPU-intensive data processing without blocking
#nodejs#worker-threads
typescriptintermediate
Node.js Stream Pipeline with Transform
Build efficient data processing pipelines using Node.js streams for large file handling.
Best for: Processing large CSV files without loading into memory
#nodejs#streams
typescriptintermediate
TypeScript Typed Event Emitter
Create type-safe event emitters in Node.js with full TypeScript support and autocomplete.
Best for: Type-safe pub/sub communication between modules
#nodejs#events
typescriptintermediate
Node.js Graceful Shutdown Handler
Implement graceful shutdown to properly close connections and finish requests before exit.
Best for: Production Node.js server reliability
#nodejs#shutdown