DanF
DanF

Reputation: 589

Quitting Node.js Program and Opening Another in Terminal

I'd like to have a condition in my current Node.js program where it will quit from occupying the command prompt and open another command line application instead.

What is the process that would accomplish this?

Upvotes: 0

Views: 363

Answers (1)

Brian
Brian

Reputation: 3334

If all you want to do is open another terminal, you can simply spawn a new terminal process. Which terminal your particular linux distribution uses you will have to figure out, but for the purposes of answering here, I will use xterm. You can spawn the process by the following command:

var spawn = require('child_process').spawn;
var oTerminalProcess = spawn("xterm", []);

Now you will pop open another terminal that should give you access to do whatever you need to do. You can later on close the process with the following command:

oTerminalProcess.kill();

You will probably want to use spawn instead of exec because exec will have buffer overflow problems after the child process outputs > 200 kB (http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback)

Of course all of this assumes some sort of GUI desktop type environment. If you wanted to do this all from a single console when a GUI isn't running, that's going to be a whole different problem.

If that is what you want to do you are going to have to attach event listeners to process stdin (http://nodejs.org/api/process.html#process_process_stdin) and push directly to stdout and emulate a terminal yourself using exec. This isn't terribly difficult, but I can imagine the details might get hairy for special cases. It might look something like this (which I tested on node 0.8.21 and it was working for me):

var exec= require('child_process').exec;
process.stdin.resume();
process.stdin.setEncoding('utf8');
var sInputBuffer = "";

process.stdout.write("$Prompt: ");

process.stdin.on('data', function(chunk) {
  sInputBuffer += chunk;
  if(chunk === "quit\n")
  { process.stdin.pause();
  }
  else
  {
      exec(sInputBuffer, function(error, stdout, stderr){
        if(stdout.length > 0)
        {  process.stdout.write(stdout);  }
        else
        {  process.stdout.write(stderr);  }

         sInputBuffer = "";
         process.stdout.write("\n$Prompt:");
      });
    }

});

Note I've got it setup for "quit" killing the program or in your case killing the stdin stream accepting input. One problem you will have to overcome may be intercepting ctrl-c commands. That right now kills the whole node, but you may want it to simply kill the command you were executing. That will be some more work for sure but nothing you can't overcome.

At any rate, that should give you a couple of options to work with. Hope this helps.

Upvotes: 1

Related Questions