2

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.

2 Answers 2

1

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'));
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.