Node.js REPL & CLI

Complete practical guide with commands and project examples

Hands-on Interactive Beginner to Advanced

Table of Contents

  1. What is REPL?
  2. Getting Started with REPL
  3. REPL Features & Commands
  4. Advanced REPL Usage
  5. Creating CLI Applications
  6. Working with process.argv
  7. Using Readline Module
  8. Building Interactive CLI Tools
  9. CLI Frameworks & Libraries
  10. Practical Examples

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 CaseBenefit
Testing snippetsTry code without creating files
DebuggingTest functions and logic quickly
LearningExperiment with Node.js APIs
PrototypingRapidly validate ideas
CalculationsUse 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

CommandDescriptionExample
.helpShow all commands> .help
.exitExit REPL> .exit
.saveSave session> .save session.js
.loadLoad JS file> .load app.js
.clearClear context> .clear
.editorEditor mode> .editor
.breakAbort 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
LibraryPurpose
commanderCLI command framework
yargsArgument parsing
inquirerInteractive prompts
chalkColored console output
oraLoading 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 (0 success, non-zero errors).
  • Handle signals (SIGINT, SIGTERM) gracefully.
  • Add centralized error handling for uncaught exceptions/rejections.
  • Show progress indicators for long-running commands.