Providing Node.js Ink CLI boilerplate
The snippet includes a minimal CLI app using Ink with a spinner and progress bar, spawning a cross-platform child process (a Node timer), and handling SIGINT to clean up the child process and unmount the app. It also outlines a sample package.json with dependencies and uses ES modules imports.
Below is a minimal boilerplate for a Node.js CLI that uses Ink for a React-style terminal UI with spinners and a progress bar. It also demonstrates how to spawn a child process and clean it up on SIGINT (Ctrl+C).
package.json
{
"name": "ink-cli-boilerplate",
"version": "1.0.0",
"type": "module",
"bin": "cli.js",
"scripts": {
"start": "node cli.js"
},
"dependencies": {
"ink": "^3.2.0",
"ink-spinner": "^5.1.0",
"ink-progress-bar": "^1.0.0",
"react": "^18.2.0"
}
}
cli.js
#!/usr/bin/env node
import React, { useEffect, useState } from 'react';
import { render, Box, Text } from 'ink';
import Spinner from 'ink-spinner';
import ProgressBar from 'ink-progress-bar';
import { spawn } from 'child_process';
let childProcess = null;
const App = () => {
const [progress, setProgress] = useState(0);
const [status, setStatus] = useState('Starting...');
const [childPID, setChildPID] = useState(null);
useEffect(() => {
// Spawn a long-running child process (cross-platform example)
childProcess = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 5000)'], {
stdio: 'ignore'
});
setChildPID(childProcess.pid);
setStatus('Child process running...');
childProcess.on('exit', (code) => {
setStatus(`Child exited with code ${code}`);
setProgress(1);
});
// Simulate progress updates
const interval = setInterval(() => {
setProgress((prev) => {
const next = prev + 0.1;
if (next >= 1) clearInterval(interval);
return Math.min(next, 1);
});
}, 500);
// Cleanup if component unmounts or process is killed
return () => {
clearInterval(interval);
if (childProcess && !childProcess.killed) {
childProcess.kill('SIGINT');
}
};
}, []);
return (
<Box flexDirection="column">
<Box marginBottom={1}>
<Text color="green">
<Spinner type="dots" />{' '}
</Text>
<Text>{status}</Text>
</Box>
<Box marginBottom={1}>
<Text>Progress: </Text>
<Box marginLeft={1} width={20}>
<ProgressBar percent={progress} />
</Box>
</Box>
<Box>
<Text>Child PID: {childPID ?? 'N/A'}</Text>
</Box>
</Box>
);
};
const { unmount } = render(<App />);
// Handle SIGINT to ensure child is killed
process.on('SIGINT', () => {
if (childProcess && !childProcess.killed) {
childProcess.kill('SIGINT');
}
unmount();
process.exit();
});
How to run
- Install dependencies:
npm install
- Start the CLI:
npm start
- Press
Ctrl+C to test cleanup of the child process.