🎮 Node.js CLI Development: Your Computer’s Remote Control
The Story: Becoming a Command-Line Wizard
Imagine you have a magic wand that can talk to your computer. Instead of clicking buttons, you type words and your computer listens. That’s what CLI (Command Line Interface) tools are! Today, you’ll learn to build your own magic wands with Node.js.
🎯 What You’ll Master
Think of building a CLI tool like building a robot assistant:
- Arguments = Instructions you give your robot
- stdin/stdout = Your robot’s ears and mouth
- Environment = The room your robot works in
- Watch Mode = Your robot that never sleeps
1. Command Line Arguments: Giving Orders to Your Program
What Are They?
When you type node myapp.js hello world, the words “hello” and “world” are arguments. They’re like giving instructions to a friend.
graph TD A["You Type Command"] --> B["node myapp.js hello world"] B --> C["process.argv"] C --> D["0: path to node"] C --> E["1: path to script"] C --> F["2: 'hello'"] C --> G["3: 'world'"]
Simple Example
// greet.js
const name = process.argv[2];
console.log(`Hello, ${name}!`);
// Run: node greet.js Sarah
// Output: Hello, Sarah!
Real Life Connection
It’s like ordering food:
node pizza.js large pepperoni- Your program knows: size = large, topping = pepperoni
2. Working with stdin/stdout: Your Program’s Ears and Mouth
The Concept
- stdin (Standard Input) = Your program’s EARS 👂
- stdout (Standard Output) = Your program’s MOUTH 🗣️
Your program can LISTEN and TALK!
Reading Input Example
// ask.js
process.stdout.write('What is your name? ');
process.stdin.once('data', (data) => {
const name = data.toString().trim();
console.log(`Nice to meet you, ${name}!`);
process.exit();
});
Piping Data (Advanced Magic)
echo "Hello" | node upper.js
# Takes "Hello", makes it "HELLO"
// upper.js
let data = '';
process.stdin.on('data', chunk => {
data += chunk;
});
process.stdin.on('end', () => {
console.log(data.toUpperCase());
});
3. Environment Configuration: The Secret Settings Room
What Is Environment?
Imagine your app is a chef. The environment is the kitchen it works in. Different kitchens have different ingredients available!
graph TD A["Your App"] --> B{Which Kitchen?} B -->|Development| C["Local Database<br>Debug Mode ON"] B -->|Production| D["Real Database<br>Debug Mode OFF"]
Accessing Environment Variables
// config.js
const dbHost = process.env.DATABASE_HOST;
const apiKey = process.env.API_KEY;
console.log(`Connecting to: ${dbHost}`);
Setting Environment Variables
On Mac/Linux:
DATABASE_HOST=localhost node app.js
On Windows (PowerShell):
$env:DATABASE_HOST="localhost"; node app.js
4. NODE_ENV Variable: Development vs Production Mode
The Story
Think of NODE_ENV as a costume change for your app:
- Development = Casual clothes (relaxed, more errors shown)
- Production = Formal suit (optimized, secure)
How It Works
// app.js
if (process.env.NODE_ENV === 'production') {
console.log('🚀 Running in PRODUCTION');
// Hide detailed errors
// Enable caching
} else {
console.log('đź”§ Running in DEVELOPMENT');
// Show all errors
// Disable caching
}
Setting NODE_ENV
# Development (default)
node app.js
# Production
NODE_ENV=production node app.js
5. Native Watch Mode: The Auto-Restart Robot
The Problem
Every time you change code, you must restart. Annoying!
The Solution: Watch Mode
Node.js 18+ has built-in watch mode. It watches your files and restarts automatically!
node --watch app.js
graph LR A["You Edit Code"] --> B["Node Detects Change"] B --> C["Auto Restart"] C --> D["New Code Running!"]
Watch Specific Files
node --watch-path=./src app.js
This only watches the src folder. Ignores other changes.
6. Native .env File Support: Secrets in a File
What Is a .env File?
It’s a secret diary for your app’s passwords and settings!
# .env file
DATABASE_URL=mongodb://localhost:27017
API_KEY=super_secret_123
PORT=3000
Loading with Node.js 20+
node --env-file=.env app.js
Now your app can read these secrets:
// app.js
console.log(process.env.DATABASE_URL);
console.log(process.env.API_KEY);
// Works! No extra packages needed!
Multiple Environment Files
# Development settings
node --env-file=.env.development app.js
# Production settings
node --env-file=.env.production app.js
7. Creating CLI Tools: Building Your Own Commands
The Dream
What if you could type greet Sarah instead of node greet.js Sarah?
You can! Let’s build a real CLI tool.
Step 1: Create Your Script
// bin/hello-cli.js
#!/usr/bin/env node
const name = process.argv[2] || 'World';
console.log(`đź‘‹ Hello, ${name}!`);
Step 2: Update package.json
{
"name": "hello-cli",
"version": "1.0.0",
"bin": {
"greet": "./bin/hello-cli.js"
}
}
Step 3: Link It Globally
npm link
Step 4: Use It Anywhere!
greet Sarah
# Output: đź‘‹ Hello, Sarah!
8. Shebang and Executable Scripts: The Magic First Line
What Is a Shebang?
The shebang (#!) is the first line that tells your computer: “Use Node.js to run this!”
#!/usr/bin/env node
It’s like a name tag that says: “I speak Node.js!”
graph TD A["#!/usr/bin/env node"] --> B["Computer reads this"] B --> C["Finds Node.js"] C --> D["Runs your script with Node"]
Making Scripts Executable
Step 1: Add the shebang
#!/usr/bin/env node
console.log('I am executable!');
Step 2: Make it executable (Mac/Linux)
chmod +x myscript.js
Step 3: Run directly
./myscript.js
# No need to type "node" first!
Why #!/usr/bin/env node?
#!/usr/bin/node= Node must be EXACTLY here#!/usr/bin/env node= Find Node wherever it is âś…
The second option works on ANY computer!
🎓 Putting It All Together: A Complete CLI Tool
Here’s a mini-project combining everything:
#!/usr/bin/env node
// weather-cli.js - A fake weather CLI
const city = process.argv[2];
const unit = process.env.TEMP_UNIT || 'celsius';
if (!city) {
process.stderr.write('Error: City required!\n');
process.exit(1);
}
const temp = Math.floor(Math.random() * 30);
const display = unit === 'fahrenheit'
? `${temp * 1.8 + 32}°F`
: `${temp}°C`;
console.log(`🌤️ Weather in ${city}: ${display}`);
Usage:
# Basic
./weather-cli.js London
# Output: 🌤️ Weather in London: 22°C
# With environment variable
TEMP_UNIT=fahrenheit ./weather-cli.js London
# Output: 🌤️ Weather in London: 71.6°F
🚀 Quick Reference
| Concept | What It Does | Example |
|---|---|---|
process.argv |
Get command arguments | process.argv[2] |
process.stdin |
Read input | stdin.on('data') |
process.stdout |
Write output | stdout.write() |
process.env |
Access environment | process.env.PORT |
NODE_ENV |
Dev vs Production | development or production |
--watch |
Auto-restart | node --watch app.js |
--env-file |
Load .env | node --env-file=.env |
| Shebang | Make executable | #!/usr/bin/env node |
🎯 You Did It!
You now know how to:
- âś… Read command line arguments
- âś… Work with stdin and stdout
- âś… Configure environments
- âś… Use NODE_ENV properly
- âś… Enable watch mode
- âś… Load .env files natively
- âś… Create real CLI tools
- âś… Make scripts executable with shebangs
You’re officially a CLI wizard! 🧙‍♂️
Go build something amazing. Your terminal is waiting.
