rocket-shell
v2.1.0
Published
A modern, flexible shell command execution library for Node.js, supporting tagged template literals, custom spawn options, and streamlined remote execution via SSH.
Readme
rocket-shell
A modern, flexible shell command execution library for Node.js, supporting tagged template literals, custom spawn options, and streamlined remote execution via SSH.
Features
- 🚀 Modern ES Module - Built for ES2022+ with proper ES module exports
- 📝 Template Literals - Run shell commands using tagged template literals:
await $echo hello world`` - ⚙️ Custom Options - Pass Node.js
child_process.spawnoptions - � Output Control - Fine-grained control over console output and stream redirection
- �🔗 Template Composition - Safely compose commands with template values
- 🌐 SSH Remote Execution - Built-in SSH support with clean syntax
- 📦 TypeScript Ready - Full TypeScript definitions included
- 🎯 Zero Dependencies - Lightweight with no external dependencies
Installation
npm install rocket-shellQuick Start
import $ from 'rocket-shell';
// Simple command execution
const result = await $`echo "Hello, World!"`;
console.log(result); // "Hello, World!"
// Template value interpolation
const name = 'rocket-shell';
const greeting = await $`echo "Welcome to ${name}"`;
console.log(greeting); // "Welcome to rocket-shell"Core Usage
Basic Command Execution
import $ from 'rocket-shell';
// Simple commands
const date = await $`date`;
const files = await $`ls -la`;
// Commands with arguments
const content = await $`cat package.json`;Template Value Interpolation
// Safe value interpolation
const filename = 'example.txt';
const content = 'Hello World';
await $`echo "${content}" > ${filename}`;
// Multiple values
const user = 'admin';
const group = 'staff';
await $`chown ${user}:${group} ${filename}`;Custom Spawn Options
// Execute with shell interpretation
const result = await $({ shell: true })`for i in {1..5}; do echo $i; done`;
// Set working directory
const gitStatus = await $({ cwd: '/path/to/repo' })`git status`;
// Custom environment variables
const result = await $({
env: { ...process.env, NODE_ENV: 'production' }
})`npm run build`;
// Timeout after 5 seconds
const result = await $({
timeout: 5000
})`long-running-command`;Console Output Control
Control whether command output is echoed to the console:
// Silent execution (default) - no console output
const result = await $`echo "This won't appear in console"`;
// Enable console echoing
const result = await $({ echo: true })`echo "This will appear in console"`;
// Disable console echoing explicitly
const result = await $({ echo: false })`echo "This won't appear in console"`;
// Selective output control
const result = await $({
echo: {
stdout: true, // Show stdout in console
stderr: false // Hide stderr from console
}
})`some-command`;
// Custom output streams
import { createWriteStream } from 'fs';
const logFile = createWriteStream('command.log');
const result = await $({
echo: {
stdout: logFile, // Redirect stdout to file
stderr: process.stderr // Keep stderr on console
}
})`some-command`;Remote Execution (SSH)
Basic SSH Usage
// Execute command on remote host
const hostname = await $({ shell: 'ssh user@remote-host' })`hostname`;
// Multiple commands
const info = await $({ shell: 'ssh user@remote-host' })`
uname -a &&
df -h &&
free -m
`;SSH with Complex Commands
// Remote shell operations
const deployResult = await $({ shell: 'ssh deploy@server' })`
cd /app &&
git pull origin main &&
npm install --production &&
pm2 restart app
`;
// Remote file operations
const backupResult = await $({ shell: 'ssh backup@server' })`
tar -czf backup-$(date +%Y%m%d).tar.gz /important/data
`;Advanced Usage
Command Chaining
// Using template values for dynamic commands
const branch = 'feature/new-feature';
const result = await $`git checkout ${branch} && git pull origin ${branch}`;
// Complex pipeline
const compressed = await $({ shell: true })`
find . -name "*.log" -type f |
xargs gzip -9
`;Error Handling
try {
const result = await $`some-command-that-might-fail`;
console.log('Success:', result);
} catch (error) {
console.error('Command failed:', error);
}
// With timeout
try {
const result = await $({ timeout: 10000 })`slow-command`;
} catch (error) {
if (error.signal === 'SIGTERM') {
console.log('Command timed out');
} else {
console.error('Command failed:', error);
}
}Working with Output
// Silent execution by default
const gitLog = await $`git log --oneline -n 10`;
const commits = gitLog.trim().split('\n');
commits.forEach(commit => console.log(`- ${commit}`));
// Live output streaming to console
const buildResult = await $({ echo: true })`npm run build`;
// JSON output parsing with selective echoing
const packageInfo = await $({
echo: { stdout: false, stderr: true } // Show errors but not JSON output
})`npm view . --json`;
const pkg = JSON.parse(packageInfo);
console.log(`Package: ${pkg.name}@${pkg.version}`);
// Log command output to file while keeping errors visible
import { createWriteStream } from 'fs';
const logStream = createWriteStream('./deploy.log', { flags: 'a' });
const deployResult = await $({
echo: {
stdout: logStream, // Log output to file
stderr: process.stderr // Keep errors on console
}
})`./deploy.sh`;API Reference
$command``
Executes a shell command using tagged template literals.
Returns: Promise<string> - The command's stdout output
const output = await $`echo hello`;$({ options })command``
Executes a shell command with custom spawn options.
Parameters:
options: Partial<SpawnOptions>- Node.js spawn options
Returns: Function that accepts a template literal and returns Promise<string>
const output = await $({ shell: true, cwd: '/tmp' })`pwd`;SpawnOptions
Extends Node.js child_process.SpawnOptions:
echo: boolean | { stdout?: boolean|Writable|null, stderr?: boolean|Writable|null }- Control console outputtrue: Echo both stdout and stderr to consolefalse: Silent execution (default)- Object: Fine-grained control over output streams
shell: boolean | string- Execute in shell or specify SSH commandcwd: string- Working directoryenv: object- Environment variablestimeout: number- Execution timeout in milliseconds- And all other standard Node.js spawn options
SSH Shell Syntax
For SSH execution, use the shell option with SSH command:
$({ shell: 'ssh [user@]host [options]' })`remote-command`TypeScript Support
Full TypeScript definitions are included:
import $ from 'rocket-shell';
import { Writable } from 'stream';
// Type-safe spawn options
interface CustomOptions {
shell?: boolean | string;
echo?: boolean | {
stdout?: boolean | Writable | null;
stderr?: boolean | Writable | null;
};
timeout?: number;
}
const result: string = await $({
shell: true,
echo: { stdout: true, stderr: false },
timeout: 5000
} as CustomOptions)`echo "typed"`;Requirements
- Node.js >= 24.2.0
- ES Module support (
"type": "module"in package.json)
Migration from v1.x
Version 2.0+ is a major rewrite with breaking changes:
- Now requires ES modules (
"type": "module") - Updated to modern Node.js requirements (>= 24.2.0)
- Improved SSH handling
- Better TypeScript support
License
ISC
Contributing
Issues and pull requests welcome at https://github.com/rocketcode-dev/rocket-shell
Author
Thomas D Wilkinson
