Node.js REPL & CLI
Complete practical guide with commands and project examples
Hands-on
Interactive
Beginner to Advanced
Table of Contents
What is REPL?
REPL stands for Read-Eval-Print-Loop. It's an interactive environment that reads input, evaluates code, prints result, and loops for the next command.
Why Use REPL?
| Use Case | Benefit |
|---|---|
| Testing snippets | Try code without creating files |
| Debugging | Test functions and logic quickly |
| Learning | Experiment with Node.js APIs |
| Prototyping | Rapidly validate ideas |
| Calculations | Use as calculator |
# Running a file (non-interactive)
node app.js
# Starting REPL (interactive)
node
Getting Started with REPL
Start REPL
node
>
First REPL Commands
> 2 + 2
4
> let name = "John"
undefined
> name
'John'
> let fruits = ["apple", "banana", "orange"]
undefined
> fruits[1]
'banana'
> function greet(name) { return `Hello ${name}!` }
undefined
> greet("Bob")
'Hello Bob!'
Exit REPL
// Ctrl+C twice, Ctrl+D, .exit, or process.exit()
> .exit
REPL Features & Commands
| Command | Description | Example |
|---|---|---|
| .help | Show all commands | > .help |
| .exit | Exit REPL | > .exit |
| .save | Save session | > .save session.js |
| .load | Load JS file | > .load app.js |
| .clear | Clear context | > .clear |
| .editor | Editor mode | > .editor |
| .break | Abort current cmd | > .break |
Underscore Variable
> 5 + 3
8
> _ + 2
10
Tab Auto-completion
> Math. // Press Tab to view methods
Advanced REPL Usage
Custom REPL
const repl = require('repl');
const r = repl.start({ prompt: 'myapp> ' });
r.context.version = '1.0.0';
r.context.add = (a, b) => a + b;
REPL History
// Up/Down arrow for history
console.log(process.env.HOME + '/.node_repl_history')
REPL Options
repl.start({
prompt: 'custom> ',
useColors: true,
ignoreUndefined: true
});
Creating CLI Applications
CLI Entry Pattern
// cli.js
console.log('Args:', process.argv.slice(2));
// node cli.js hello --name John
Working with process.argv
const args = process.argv.slice(2);
let name = 'World';
for (let i = 0; i < args.length; i++) {
if (args[i] === '--name' || args[i] === '-n') name = args[++i];
}
console.log(`Hello, ${name}!`);
Use process.env
const env = process.env.NODE_ENV || 'development';
const port = process.env.PORT || 8080;
Using Readline Module
Basic Readline
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question('What is your name? ', (answer) => {
console.log(`Hello, ${answer}!`);
rl.close();
});
Multiple Questions (Promise style)
function askQuestion(q, rl) {
return new Promise(resolve => rl.question(q, resolve));
}
Building Interactive CLI Tools
Build menu systems, todo tools, and command-based apps with readline and filesystem/network modules.
Menu Example Pattern
// show options - read input - switch case - repeat prompt
switch(choice) {
case '1': console.log('Hello'); break;
case '4': rl.close(); break;
}
CLI Frameworks & Libraries
Popular Libraries
npm install commander
npm install yargs
npm install inquirer
npm install chalk
npm install ora
| Library | Purpose |
|---|---|
| commander | CLI command framework |
| yargs | Argument parsing |
| inquirer | Interactive prompts |
| chalk | Colored console output |
| ora | Loading spinners |
Practical Examples
1) File Explorer CLI
// Commands: ls, cd, cat, pwd, exit
const fs = require('fs');
const path = require('path');
2) Backup CLI Tool
// Use commander + ora + fs to backup/restore files
program.command('backup <file>')
3) Password Generator CLI
const crypto = require('crypto');
function generatePassword(length = 12) {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
let out = '';
for (let i = 0; i < length; i++) out += chars[crypto.randomInt(0, chars.length)];
return out;
}
Best Practices
- Use proper exit codes (
0success, non-zero errors). - Handle signals (
SIGINT,SIGTERM) gracefully. - Add centralized error handling for uncaught exceptions/rejections.
- Show progress indicators for long-running commands.