This is a comprehensive request for a Node.js CLI tool boilerplate using Ink, which is a React renderer for terminal applications. I need to create a complete, production-ready boilerplate that includes:
- Ink setup for React-based terminal UI
- Spinners and progress bars
- SIGINT handling for graceful cleanup
- Child process management
- Good structure and examples
Let me create a complete solution with:
- Package structure
- Main entry point
- Reusable components for spinners and progress bars
- Process management utilities
- Error handling
- Example CLI implementation
- Documentation
I'll create multiple files that work together:
- package.json - dependencies
- src/index.js - entry point
- src/components/Spinner.js - spinner component
- src/components/ProgressBar.js - progress bar component
- src/utils/ProcessManager.js - handle child processes and SIGINT
- src/commands/example.js - example command
- src/utils/logger.js - logging utilities
- README.md - documentation
- .gitignore
Let me build this out properly.
Node.js CLI Tool Boilerplate with Ink
I'll create a complete, production-ready CLI boilerplate with React-based terminal UI, process management, and graceful cleanup.
1. Project Structure & package.json
{
"name": "ink-cli-boilerplate",
"version": "1.0.0",
"description": "A feature-rich Node.js CLI boilerplate using Ink for React terminal UIs",
"type": "module",
"main": "dist/index.js",
"bin": {
"my-cli": "./dist/index.js"
},
"scripts": {
"build": "babel src --out-dir dist --extensions .js,.jsx",
"dev": "node --loader ./loader.js src/index.js",
"start": "node dist/index.js",
"test": "node --test",
"clean": "rm -rf dist node_modules"
},
"keywords": [
"cli",
"ink",
"react",
"terminal",
"ui"
],
"author": "",
"license": "MIT",
"dependencies": {
"chalk": "^5.3.0",
"commander": "^11.1.0",
"ink": "^4.4.1",
"ink-spinner": "^4.1.1",
"react": "^18.2.0"
},
"devDependencies": {
"@babel/cli": "^7.23.5",
"@babel/core": "^7.23.5",
"@babel/preset-env": "^7.23.5",
"@babel/preset-react": "^7.23.3"
}
}
2. Babel Configuration
.babelrc
{
"presets": [
["@babel/preset-env", { "targets": { "node": "18" } }],
["@babel/preset-react", { "runtime": "automatic" }]
]
}
3. Loader for ES Modules (for development)
loader.js
import { createRequire } from 'module';
import { fileURLToPath } from 'url';
import path from 'path';
const require = createRequire(import.meta.url);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export async function initialize() {
// Register JSX transformation if needed
}
4. Process Manager Utility
src/utils/ProcessManager.js
import { EventEmitter } from 'events';
import { spawn } from 'child_process';
class ProcessManager extends EventEmitter {
constructor() {
super();
this.processes = new Set();
this.isCleaningUp = false;
// Handle SIGINT (Ctrl+C)
this.handleSigInt = this.handleSigInt.bind(this);
process.on('SIGINT', this.handleSigInt);
// Handle SIGTERM
process.on('SIGTERM', () => this.cleanup());
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
this.cleanup();
});
}
async handleSigInt() {
if (this.isCleaningUp) return;
console.log('\n\n🛑 Received SIGINT, cleaning up...');
await this.cleanup();
process.exit(0);
}
/**
* Spawn a child process and track it
*/
spawnProcess(command, args = [], options = {}) {
return new Promise((resolve, reject) => {
const defaultOptions = {
stdio: 'pipe',
detached: false,
...options,
};
const child = spawn(command, args, defaultOptions);
this.processes.add(child);
let stdout = '';
let stderr = '';
if (child.stdout) {
child.stdout.on('data', (data) => {
stdout += data.toString();
this.emit('stdout', data.toString());
});
}
if (child.stderr) {
child.stderr.on('data', (data) => {
stderr += data.toString();
this.emit('stderr', data.toString());
});
}
child.on('close', (code) => {
this.processes.delete(child);
if (code === 0) {
resolve({ code, stdout, stderr });
} else {
reject(new Error(`Process exited with code ${code}: ${stderr}`));
}
});
child.on('error', (error) => {
this.processes.delete(child);
reject(error);
});
});
}
/**
* Execute a shell command
*/
exec(command, options = {}) {
return this.spawnProcess('sh', ['-c', command], options);
}
/**
* Get number of running processes
*/
getProcessCount() {
return this.processes.size;
}
/**
* Stop all running processes
*/
async cleanup() {
if (this.isCleaningUp) return;
this.isCleaningUp = true;
const cleanupPromises = Array.from(this.processes).map((child) => {
return new Promise((resolve) => {
if (child.killed) {
resolve();
return;
}
// Send SIGTERM first
child.kill('SIGTERM');
// Force kill after timeout
const timeout = setTimeout(() => {
if (!child.killed) {
child.kill('SIGKILL');
}
resolve();
}, 5000);
child.on('exit', () => {
clearTimeout(timeout);
resolve();
});
});
});
await Promise.all(cleanupPromises);
this.processes.clear();
// Remove signal handlers
process.removeListener('SIGINT', this.handleSigInt);
process.removeListener('SIGTERM', this.cleanup);
this.emit('cleanup-complete');
}
/**
* Register process cleanup on exit
*/
onExit(callback) {
this.on('cleanup-complete', callback);
}
}
// Export singleton
export default new ProcessManager();
5. Spinner Component
src/components/Spinner.jsx
import React from 'react';
import { Box, Text } from 'ink';
import Spinner from 'ink-spinner';
export default function LoadingSpinner({
message = 'Loading...',
type = 'dots'
}) {
return (
<Box>
<Spinner type={type} />
<Box marginLeft={1}>
<Text>{message}</Text>
</Box>
</Box>
);
}
6. Progress Bar Component
src/components/ProgressBar.jsx
import React from 'react';
import { Box, Text } from 'ink';
export default function ProgressBar({
current = 0,
total = 100,
width = 30,
label = 'Progress',
color = 'cyan'
}) {
const percentage = Math.min((current / total) * 100, 100);
const filledWidth = Math.round((width * percentage) / 100);
const emptyWidth = width - filledWidth;
const filled = '█'.repeat(Math.max(filledWidth, 0));
const empty = '░'.repeat(Math.max(emptyWidth, 0));
const percentageStr = percentage.toFixed(1);
return (
<Box flexDirection="column">
<Text>{label}</Text>
<Box>
<Text>{filled}</Text>
<Text color="gray">{empty}</Text>
<Text marginLeft={1}>{percentageStr}%</Text>
</Box>
<Text color="gray">{current} / {total}</Text>
</Box>
);
}
7. Custom Hooks
src/hooks/useAsync.js
import { useState, useEffect } from 'react';
export function useAsync(asyncFunction, immediate = true) {
const [status, setStatus] = useState('idle');
const [value, setValue] = useState(null);
const [error, setError] = useState(null);
const execute = async () => {
setStatus('pending');
setValue(null);
setError(null);
try {
const response = await asyncFunction();
setValue(response);
setStatus('success');
return response;
} catch (err) {
setError(err);
setStatus('error');
throw err;
}
};
useEffect(() => {
if (immediate) {
execute();
}
}, []);
return { execute, status, value, error };
}
8. Logger Utility
src/utils/logger.js
import chalk from 'chalk';
export const logger = {
info: (message) => {
console.log(chalk.blue('ℹ'), message);
},
success: (message) => {
console.log(chalk.green('✓'), message);
},
warning: (message) => {
console.log(chalk.yellow('⚠'), message);
},
error: (message) => {
console.log(chalk.red('✗'), message);
},
debug: (message) => {
if (process.env.DEBUG) {
console.log(chalk.gray('→'), message);
}
},
section: (title) => {
console.log('\n' + chalk.bold.cyan(`▶ ${title}`));
},
};
9. Example Command Component
src/commands/Example.jsx
import React, { useState, useEffect } from 'react';
import { Box, Text } from 'ink';
import LoadingSpinner from '../components/Spinner.jsx';
import ProgressBar from '../components/ProgressBar.jsx';
import processManager from '../utils/ProcessManager.js';
import { logger } from '../utils/logger.js';
export default function ExampleCommand({ duration = 5000 }) {
const [step, setStep] = useState('downloading');
const [progress, setProgress] = useState(0);
const [output, setOutput] = useState([]);
useEffect(() => {
let interval;
let timeout;
const runExample = async () => {
try {
// Step 1: Simulated download
logger.section('Simulating File Download');
setStep('downloading');
setProgress(0);
interval = setInterval(() => {
setProgress((prev) => {
if (prev >= 100) {
clearInterval(interval);
return 100;
}
return prev + Math.random() * 20;
});
}, 200);
// Simulate with actual sleep
await new Promise((resolve) => setTimeout(resolve, 2000));
setProgress(100);
logger.success('Download complete');
clearInterval(interval);
// Step 2: Processing
logger.section('Processing Files');
setStep('processing');
setProgress(0);
interval = setInterval(() => {
setProgress((prev) => {
if (prev >= 100) {
clearInterval(interval);
return 100;
}
return prev + Math.random() * 15;
});
}, 150);
await new Promise((resolve) => setTimeout(resolve, 2000));
setProgress(100);
logger.success('Processing complete');
clearInterval(interval);
// Step 3: Run child process
logger.section('Running Child Process');
setStep('running-child');
setOutput([]);
try {
const result = await processManager.exec('echo "Hello from child process" && sleep 1 && echo "Done"', {
stdio: 'inherit',
});
logger.success('Child process completed successfully');
setOutput([...output, result.stdout]);
} catch (err) {
logger.error(`Child process failed: ${err.message}`);
}
setStep('complete');
} catch (err) {
logger.error(`Error: ${err.message}`);
setStep('error');
}
};
runExample();
return () => {
if (interval) clearInterval(interval);
if (timeout) clearTimeout(timeout);
};
}, []);
if (step === 'complete') {
return (
<Box flexDirection="column" marginTop={1} marginBottom={1}>
<Text color="green" bold>
✓ All operations completed successfully!
</Text>
</Box>
);
}
if (step === 'error') {
return (
<Box flexDirection="column" marginTop={1} marginBottom={1}>
<Text color="red" bold>
✗ An error occurred
</Text>
</Box>
);
}
return (
<Box flexDirection="column" marginTop={1} marginBottom={1}>
<Text bold>Running CLI Operations</Text>
<Box marginTop={1} marginBottom={1}>
{(step === 'downloading' || step === 'processing' || step === 'running-child') ? (
<LoadingSpinner message={`${step.toUpperCase()}...`} />
) : null}
</Box>
{(step === 'downloading' || step === 'processing') && (
<Box marginTop={1} marginBottom={1}>
<ProgressBar current={Math.round(progress)} total={100} label={step} />
</Box>
)}
{output.length > 0 && (
<Box flexDirection="column" marginTop={1}>
<Text bold>Output:</Text>
{output.map((line, idx) => (
<Text key={idx} color="gray">
{line}
</Text>
))}
</Box>
)}
</Box>
);
}
10. Main Entry Point
src/index.js
#!/usr/bin/env node
import { render } from 'ink';
import { Command } from 'commander';
import React from 'react';
import ExampleCommand from './commands/Example.jsx';
import CLIApp from './App.jsx';
import processManager from './utils/ProcessManager.js';
const program = new Command();
program
.name('my-cli')
.description('A feature-rich CLI tool built with Ink and React')
.version('1.0.0');
program
.command('example')
.description('Run example operations')
.option('--duration <ms>', 'Duration in milliseconds', '5000')
.action((options) => {
const duration = parseInt(options.duration);
const { unmount } = render(
React.createElement(ExampleCommand, { duration })
);
processManager.onExit(() => {
unmount();
process.exit(0);
});
});
program
.command('interactive')
.description('Run interactive CLI')
.action(() => {
const { unmount } = render(React.createElement(CLIApp));
processManager.onExit(() => {
unmount();
process.exit(0);
});
});
program.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp();
}
11. Interactive App Component
src/App.jsx
import React, { useState } from 'react';
import { Box, Text } from 'ink';
import SelectInput from 'ink-select-input';
import TextInput from 'ink-text-input';
import ProgressBar from './components/ProgressBar.jsx';
import LoadingSpinner from './components/Spinner.jsx';
import processManager from './utils/ProcessManager.js';
import { logger } from './utils/logger.js';
export default function CLIApp() {
const [screen, setScreen] = useState('menu');
const [selectedIndex, setSelectedIndex] = useState(0);
const [progress, setProgress] = useState(0);
const menuItems = [
{ label: 'Run Download Simulation', value: 'download' },
{ label: 'Run Processing Task', value: 'process' },
{ label: 'Run Child Process Example', value: 'child' },
{ label: 'Exit', value: 'exit' },
];
const handleMenuSelect = async (item) => {
if (item.value === 'exit') {
await processManager.cleanup();
process.exit(0);
}
setScreen(item.value);
// Simulate the selected task
const interval = setInterval(() => {
setProgress((prev) => {
if (prev >= 100) {
clearInterval(interval);
setTimeout(() => setScreen('menu'), 1000);
return 100;
}
return prev + Math.random() * 20;
});
}, 100);
};
if (screen === 'menu') {
return (
<Box flexDirection="column" padding={1}>
<Box marginBottom={1}>
<Text bold cyan>
🚀 Welcome to Interactive CLI
</Text>
</Box>
<SelectInput
items={menuItems}
onSelect={handleMenuSelect}
selectedIndex={selectedIndex}
onHighlight={(item) => {
const idx = menuItems.findIndex((i) => i.value === item.value);
setSelectedIndex(idx);
}}
/>
</Box>
);
}
return (
<Box flexDirection="column" padding={1}>
<Box marginBottom={1}>
<Text bold cyan>
{screen.toUpperCase()}
</Text>
</Box>
<LoadingSpinner message={`Running ${screen}...`} />
<Box marginTop={1}>
<ProgressBar current={Math.round(progress)} total={100} />
</Box>
<Box marginTop={1}>
<Text color="gray" fontSize="small">
Press Ctrl+C to cancel
</Text>
</Box>
</Box>
);
}
12. Advanced Example - Long Running Process
src/commands/LongRunning.jsx
import React, { useState, useEffect } from 'react';
import { Box, Text } from 'ink';
import LoadingSpinner from '../components/Spinner.jsx';
import ProgressBar from '../components/ProgressBar.jsx';
import processManager from '../utils/ProcessManager.js';
import { logger } from '../utils/logger.js';
export default function LongRunningCommand() {
const [tasks, setTasks] = useState([
{ id: 1, name: 'Task 1', progress: 0, status: 'running' },
{ id: 2, name: 'Task 2', progress: 0, status: 'waiting' },
{ id: 3, name: 'Task 3', progress: 0, status: 'waiting' },
]);
useEffect(() => {
const intervals = [];
tasks.forEach((task) => {
if (task.status === 'running' && task.progress < 100) {
const interval = setInterval(() => {
setTasks((prevTasks) =>
prevTasks.map((t) => {
if (t.id === task.id) {
const newProgress = Math.min(t.progress + Math.random() * 10, 100);
const newStatus = newProgress === 100 ? 'completed' : 'running';
if (newProgress === 100) {
logger.success(`${t.name} completed`);
}
return { ...t, progress: newProgress, status: newStatus };
}
// Start next task when previous completes
if (t.status === 'waiting' && prevTasks[prevTasks.indexOf(t) - 1]?.status === 'completed') {
if (t.id === task.id + 1) {
logger.info(`Starting ${t.name}`);
return { ...t, status: 'running' };
}
}
return t;
})
);
}, 200);
intervals.push(interval);
}
});
return () => intervals.forEach((interval) => clearInterval(interval));
}, [tasks]);
const allCompleted = tasks.every((task) => task.status === 'completed');
if (allCompleted) {
return (
<Box flexDirection="column" marginTop={1} marginBottom={1}>
<Text color="green" bold>
✓ All tasks completed successfully!
</Text>
</Box>
);
}
return (
<Box flexDirection="column" marginTop={1} marginBottom={1}>
<Text bold>Running Multiple Tasks</Text>
{tasks.map((task) => (
<Box key={task.id} flexDirection="column" marginTop={1} borderStyle="round" borderColor="gray" padding={1}>
<Box justifyContent="space-between">
<Text>{task.name}</Text>
<Text
color={
task.status === 'completed'
? 'green'
: task.status === 'running'
? 'yellow'
: 'gray'
}
>
{task.status}
</Text>
</Box>
<Box marginTop={1}>
<ProgressBar
current={Math.round(task.progress)}
total={100}
width={25}
/>
</Box>
</Box>
))}
</Box>
);
}
13. README Documentation
README.md
# Ink CLI Boilerplate
A production-ready Node.js CLI tool boilerplate using Ink for React-based terminal UIs.
## Features
- 🎨 React-based terminal UI with Ink
- ⚡ Reusable components (Spinners, Progress Bars)
- 🔄 Child process management with graceful cleanup
- ⏹️ SIGINT (Ctrl+C) handling for safe shutdown
- 🎯 Multiple command support with Commander.js
- 🎪 Interactive menus and prompts
- 📊 Progress tracking and async operations
- 🧹 Automatic resource cleanup
## Installation
```bash
npm install
npm run build
Usage
Run Example Command
npm start -- example
Run Interactive CLI
npm start -- interactive
Development Mode
npm run dev -- example
Project Structure
src/
├── components/
│ ├── Spinner.jsx # Loading spinner component
│ ├── ProgressBar.jsx # Progress bar component
│ └── Table.jsx # (Optional) Table component
├── commands/
│ ├── Example.jsx # Example command
│ └── LongRunning.jsx # Long-running task example
├── hooks/
│ └── useAsync.js # Async operation hook
├── utils/
│ ├── ProcessManager.js # Child process management
│ └── logger.js # Logging utilities
├── App.jsx # Main interactive app
└── index.js # CLI entry point
Process Management
The ProcessManager utility handles:
- Child Process Spawning: Create and manage child processes
- SIGINT Handling: Gracefully shutdown on Ctrl+C
- Process Cleanup: Automatic termination of running processes
- Error Handling: Catch and handle process errors
- Timeouts: Force kill processes that don't terminate
Example Usage
import processManager from './utils/ProcessManager.js';
// Spawn a process
const result = await processManager.spawnProcess('ls', ['-la']);
// Execute shell command
const output = await processManager.exec('npm install');
// Cleanup on exit
processManager.onExit(() => {
console.log('Cleaning up...');
});
Creating Commands
Create a new command component:
import React, { useState, useEffect } from 'react';
import { Box, Text } from 'ink';
import LoadingSpinner from '../components/Spinner.jsx';
export default function MyCommand({ options }) {
const [status, setStatus] = useState('running');
useEffect(() => {
// Your command logic here
}, []);
return (
<Box flexDirection="column">
<Text>My Command</Text>
{status === 'running' && <LoadingSpinner />}
</Box>
);
}
Register it in src/index.js:
program
.command('mycommand')
.description('My custom command')
.action(() => {
const { unmount } = render(React.createElement(MyCommand));
// ... setup cleanup
});
Handling Signals
The CLI automatically handles:
- SIGINT (Ctrl+C): Graceful shutdown
- SIGTERM: Termination request
- Uncaught Exceptions: Error recovery
All running processes are terminated safely before exit.
Logging
import { logger } from './utils/logger.js';
logger.info('Information');
logger.success('Success message');
logger.warning('Warning message');
logger.error('Error message');
logger.debug('Debug message'); // Only in DEBUG mode
logger.section('Section Title');
Environment Variables
DEBUG=1 npm start - Enable debug logging
Best Practices
- Always cleanup resources: Use ProcessManager for child processes
- Handle errors gracefully: Wrap async operations in try-catch
- Provide user feedback: Use spinners and progress bars
- Exit codes: Use appropriate exit codes for different scenarios
- Memory management: Clear intervals and timeouts in useEffect cleanup
Dependencies
ink - React renderer for terminal UIs
react - UI library
chalk - Terminal colors
commander - CLI framework
ink-spinner - Spinner component
Example Commands
# Show help
npm start -- --help
# Run example with custom duration
npm start -- example --duration 10000
# Run interactive mode
npm start -- interactive
# Development with auto-reload
npm run dev -- example
Troubleshooting
Port already in use
If a process hangs and doesn't cleanup:
pkill -f "node.*my-cli"
Process not cleaning up
Ensure you're using ProcessManager for all child processes and calling cleanup handlers.
Memory leaks
Check that all intervals and timeouts are cleared in useEffect cleanup functions.
License
MIT
## 14. Example .gitignore
**.gitignore**
node_modules/
dist/
*.log
.DS_Store
.env
.env.local
coverage/
.idea/
.vscode/
*.swp
*.swo
*~
## 15. Example package.json scripts for better development
**Enhanced package.json scripts section:**
```json
"scripts": {
"build": "babel src --out-dir dist --extensions .js,.jsx",
"dev": "node --loader ./loader.js src/index.js",
"start": "node dist/index.js",
"watch": "babel src --out-dir dist --extensions .js,.jsx --watch",
"test": "node --test",
"clean": "rm -rf dist node_modules",
"prepare": "npm run build",
"lint": "eslint src/",
"format": "prettier --write src/",
"example:download": "npm start -- example --duration 5000",
"example:interactive": "npm start -- interactive"
}
Key Features Explained
1. ProcessManager
- Tracks all spawned processes
- Handles SIGINT with grace period
- Force kills after timeout
- Cleanup on exit
2. Components
- Spinner: Animated loading indicator
- ProgressBar: Visual progress tracking
- Fully customizable with colors and labels
3. Signal Handling
// Automatic on SIGINT
process.on('SIGINT', async () => {
await processManager.cleanup();
process.exit(0);
});
4. Error Recovery
- Try-catch all async operations
- Graceful error display
- Process cleanup on error
This boilerplate provides everything needed for production-ready CLI tools with excellent UX and robust error handling!