js 实现 shell
使用 Node.js 实现 Shell 功能
Node.js 提供了 child_process 模块,可以执行系统命令并与之交互。以下方法展示了如何实现基本的 Shell 功能。
创建子进程执行命令
const { exec } = require('child_process');
exec('ls -l', (error, stdout, stderr) => {
if (error) {
console.error(`执行错误: ${error}`);
return;
}
console.log(`输出: ${stdout}`);
if (stderr) {
console.error(`错误输出: ${stderr}`);
}
});
实现交互式 Shell
使用 spawn 方法可以创建交互式进程:
const { spawn } = require('child_process');
const shell = spawn('bash');
shell.stdout.on('data', (data) => {
console.log(`输出: ${data}`);
});
shell.stderr.on('data', (data) => {
console.error(`错误: ${data}`);
});
shell.on('close', (code) => {
console.log(`子进程退出,代码 ${code}`);
});
// 向 Shell 发送命令
shell.stdin.write('ls -l\n');
shell.stdin.write('exit\n');
使用第三方库实现增强功能
借助 node-pty 实现伪终端
const pty = require('node-pty');
const shell = pty.spawn('bash', [], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env
});
shell.on('data', (data) => {
process.stdout.write(data);
});
process.stdin.on('data', (data) => {
shell.write(data);
});
实现 Shell 历史记录功能
const readline = require('readline');
const { exec } = require('child_process');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
historySize: 100
});
function executeCommand(command) {
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`错误: ${error.message}`);
return;
}
if (stderr) {
console.error(`错误输出: ${stderr}`);
return;
}
console.log(stdout);
rl.prompt();
});
}
rl.on('line', (line) => {
executeCommand(line.trim());
}).on('close', () => {
process.exit(0);
});
rl.setPrompt('> ');
rl.prompt();
实现 Shell 管道功能
const { spawn } = require('child_process');
const ps = spawn('ps', ['-aux']);
const grep = spawn('grep', ['node']);
ps.stdout.pipe(grep.stdin);
grep.stdout.on('data', (data) => {
console.log(`输出: ${data}`);
});
注意事项
- 执行用户输入的命令时需要注意安全性,避免命令注入攻击
- 对于长时间运行的进程,需要处理超时和错误情况
- 不同操作系统可能需要调整命令语法
- 考虑使用
chalk等库增强输出显示效果







