Node.js 发送相同的bash进程多个命令
我有以下代码:Node.js 发送相同的bash进程多个命令,node.js,bash,shell,Node.js,Bash,Shell,我有以下代码: const cp = require('child_process'); function spawnInstance () { const c = cp.spawn('bash'); return command => { return new Promise((resolve, reject) => { c.stdout.on('data', d => resolve(String(d || 'empty stdout.\n')
const cp = require('child_process');
function spawnInstance () {
const c = cp.spawn('bash');
return command => {
return new Promise((resolve, reject) => {
c.stdout.on('data', d => resolve(String(d || 'empty stdout.\n')));
c.stderr.once('data', d => reject(String(d || 'empty stderr.\n')));
c.stdin.write(`echo "${command}" | bash;`);
c.stdin.write('\n');
});
};
}
(async () => {
const bash = spawnInstance();
console.log(await bash('ls'));
console.log(await bash('cd node_modules'));
console.log(await bash('ls'));
})()
.catch(e =>
console.error(e)
);
我想做的是重用相同的bash进程,并为我运行的每个命令获取标准输出。有没有办法做到这一点,或者我需要为我运行的每个命令启动一个新的bash进程
问题是我的代码卡在
cd node\u modules
命令上。我认为在bash调用之后,不能让bash进程保持活动状态,然后用一些新调用重新进入该进程。但是,您可以在同一进程中依次运行多个bash命令,例如,使用分号分隔它们:
console.log(await bash('cd node_modules; ls'));
这说明现在有一个NPM包,它允许持久的bash进程
github url:
引自him主页:
此节点模块可用于代理长寿命的bash进程、windows控制台等。它可以工作,并已在运行最新版本节点的linux、os-x和windows主机上进行了测试