Reputation: 100370
I have the following code:
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)
);
What I want to do is to reuse the same bash process, and get the stdout for each command that I run. Is there a way to do this, or do I need to start a new bash process for each command I run?
The problem is my code gets stuck on the cd node_modules
command.
Upvotes: 2
Views: 261
Reputation: 3836
This article states that now there is an NPM package that allows for a persistent bash process.
The github url:
https://github.com/bitsofinfo/stateful-process-command-proxy
Quote from the him homepage:
This node module can be used for proxying long-lived bash process, windows console etc. It works and has been tested on both linux, os-x and windows hosts running the latest version of node.
Upvotes: 1
Reputation: 13120
I don't think you can keep a bash process alive after a bash call and then re-enter the process with some new call. You can however run multiple bash commands after each other in the same process, e.g. by separating them with semicolons:
console.log(await bash('cd node_modules; ls'));
Upvotes: 1