1

If I invoke the system method in Ruby, it will execute my command in a subshell and output everything it can. So if I put this in file.rb:

system 'vim'

And run $ ruby file.rb it launches Vim so I can use it. If I do what I thought was equivalent in Node.js and put it into file.js:

var exec = require('child_process').exec;
exec('vim');

And run $ node file.js it launches Vim but doesn't output anything (unless I catch stdout from the child process and output it myself, which won't work so well). How can I achieve what I did in Ruby with Node?

user544941
  • 1,579
  • 2
  • 12
  • 16

2 Answers2

1

As with many functions in Node, the return value is actually not returned by the function call itself, but instead passed to a callback which is passed as the function's last argument. This design allows Node's main loop to take care of other tasks while the child process runs.

If you just want to print the child's stdout output, you would do the following:

var exec = require('child_process').exec;

exec('vim', function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
});

If you also want to output stderr and the process' exit code, try this:

exec('vim', function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    console.log('exit code:', error ? error.code : 0);
});

Also note that exec() is just a convenience wrapper around spawn(), which offers a much more powerful interface and lets you use streams for stdin, stdout and stderr.

This example was taken from the Node's documentation here and was slightly modified.

regular
  • 7,697
  • 1
  • 14
  • 19
0

You can do this using node-ffi as shown in the example here: https://stackoverflow.com/a/6288426/288425

Just replace echo $USER with vim and you will get an interactive vim session.

Community
  • 1
  • 1
Rohan Singh
  • 20,497
  • 1
  • 41
  • 48