js 实现shell
使用 Node.js 实现 Shell 功能
Node.js 提供了 child_process 模块,可以执行 Shell 命令并与之交互。以下是通过不同方法实现 Shell 功能的方式:
方法 1:使用 exec 执行简单命令
const { exec } = require('child_process');
exec('ls -l', (error, stdout, stderr) => {
if (error) console.error(`Error: ${error.message}`);
if (stderr) console.error(`Stderr: ${stderr}`);
console.log(`Output: ${stdout}`);
});
exec 适用于短时间运行的命令,返回完整的缓冲输出。
方法 2:使用 spawn 处理流式输出
const { spawn } = require('child_process');
const ls = spawn('ls', ['-l']);
ls.stdout.on('data', (data) => console.log(`Output: ${data}`));
ls.stderr.on('data', (data) => console.error(`Error: ${data}`));
ls.on('close', (code) => console.log(`Process exited with code ${code}`));
spawn 适合长时间运行的命令或需要实时处理输出的场景。
方法 3:使用 execSync 同步执行

const { execSync } = require('child_process');
try {
const output = execSync('ls -l').toString();
console.log(`Output: ${output}`);
} catch (error) {
console.error(`Error: ${error.message}`);
}
同步方法会阻塞事件循环,适合脚本场景。
方法 4:创建交互式 Shell
const { spawn } = require('child_process');
const readline = require('readline');
const shell = spawn('/bin/sh', { stdio: 'inherit' });
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', (input) => {
shell.stdin.write(`${input}\n`);
});
此方法模拟终端交互,将用户输入直接传递给子进程。

安全注意事项
- 避免直接拼接用户输入到命令中,使用参数数组形式(如
spawn的第二个参数)可防止命令注入。 - 对敏感命令或长期运行的进程设置超时限制。
- 检查子进程的退出码和错误输出。
扩展功能
管道支持
const grep = spawn('grep', ['node']);
const ls = spawn('ls', ['-l']);
ls.stdout.pipe(grep.stdin);
grep.stdout.pipe(process.stdout);
通过流式管道实现类似 Unix 管道功能。
环境变量控制
spawn('echo', ['$PATH'], {
env: { ...process.env, PATH: '/custom/path' },
shell: true
});
通过 env 选项可自定义子进程的环境变量。
以上方法覆盖了从简单命令执行到复杂交互式 Shell 的实现需求,开发者可根据具体场景选择合适的方式。






