How to stream output of system process in Ruby rake task?

Often time, I use Rake to manage a number of tasks I use often, but I can’t remember the command. It’s part of building tools for yourself to make yourself more productive.

Sometimes, you use rake tasks to run servers, like so:

desc "Start the server"
task :start do
  puts `node app.js`

However, that doesn’t work. The child process blocks, and won’t return until the server exits, so that means `puts` never gets a return, and hence never executes. In addition, stdout of the child process running node isn’t connected to the stdout of the parent process running rake. Therefore, you won’t see any output from the server.

Finally, being fed up with the situation, I started looking around on google and stackoverflow, and it’s kind of an elusive question. But I finally have it. It looks like this:

desc "Start the server"
task :start do
  IO.popen("node app.js") { |f| f.each { puts line } }

As long as `node app.js` continuously flushes its stdout, we’ll get its output sent to the rake’s stdout. Yay. One less annoying thing to deal with.

[1] Reference:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s