Search code examples
rubynode.jsspawn

Spawning Ruby from Node.js - How to require within the Ruby file?


I have succesfully spawn a ruby script from my node application. However, in my Ruby script I would like to require some gems and files, and it seems that when doing a require, node.js doesn't get any response.

Here is how this looks:

var cp = require('child_process')
var ruby_child = cp.spawn('ruby',['libs/scorer/test.rb']);  

var result = '';
ruby_child.stdout.on('data', function(data) {
        result += data.toString();
});

ruby_child.on('close', function() {
        console.log(result);
});

And my Ruby script looks like this:

require 'utils' # if I remove this line, I can get the response.

# Does it have an argument?
if ARGV.nil? || ARGV.empty?
  p 'test'
  exit
end

Solution

  • That's probably the require line failed. The Ruby program sent some error status to STDERR and then exited, and your js program didn't capture STDERR output.

    Add some STDERR capture code in your js program for diagnostic information of your problem. You may probably found that the Ruby cannot find the required library in $LOAD_PATH.

    ruby_child.stderr.on('data', function(data) {
        console.log("ERROR --- " + data);
    });