title: How do I open a terminal application from node.js?
body: <p>I would like to be able to open <code>Vim</code> from node.js program running in the terminal, create some content, save and exit <code>Vim</code>, and then grab the contents of the file.</p>
  
  <p>I'm trying to do something like this:</p>
  
  <pre class="lang-coffee prettyprint-override"><code>filename = '/tmp/tmpfile-' + process.pid
  
  editor = process.env['EDITOR'] ? 'vi'
  spawn editor, [filename], (err, stdout, stderr) -&gt;
  
    text = fs.readFileSync filename
    console.log text
  </code></pre>
  
  <p>However, when this runs, it just hangs the terminal.</p>
  
  <p>I've also tried it with <code>exec</code> and got the same result.</p>
  
  <p><strong>Update:</strong></p>
  
  <p>This is complicated by the fact that this process is launched from a command typed at a prompt with <a href="http://nodejs.org/docs/latest/api/readline.html">readline</a> running.  I completely extracted the relevant parts of my latest version out to a file.  Here is it in its entirety:</p>
  
  <pre class="lang-coffee prettyprint-override"><code>{spawn} = require 'child_process'
  fs = require 'fs'
  tty = require 'tty'
  rl = require 'readline'
  
  cli = rl.createInterface process.stdin, process.stdout, null
  cli.prompt()
  
  filename = '/tmp/tmpfile-' + process.pid
  
  proc = spawn 'vim', [filename]
  
  #cli.pause()
  process.stdin.resume()
  
  indata = (c) -&gt;
      proc.stdin.write c
  process.stdin.on 'data', indata
  
  proc.stdout.on 'data', (c) -&gt;
      process.stdout.write c
  
  proc.on 'exit', () -&gt;
      tty.setRawMode false
      process.stdin.removeListener 'data', indata
  
      # Grab content from the temporary file and display it
      text = fs.readFile filename, (err, data) -&gt;
          throw err if err?  
          console.log data.toString()
  
          # Try to resume readline prompt
          cli.prompt()
  </code></pre>
  
  <p>The way it works as show above, is that it shows a prompt for a couple of seconds, and then launches in to Vim, but the TTY is messed up.  I can edit, and save the file, and the contents are printed correctly.  There is a bunch of junk printed to terminal on exit as well, and Readline functionality is broken afterward (no Up/Down arrow, no Tab completion).</p>
  
  <p>If I uncomment the <code>cli.pause()</code> line, then the TTY is OK in Vim, but I'm stuck in insert mode, and the <code>Esc</code> key doesn't work.  If I hit <code>Ctrl-C</code> it quits the child and parent process.</p>