Bluebird.js with Child Process

2014-01-14

When I started my first real Node.js application, I figured out, that it is a good thing to know what streams are. Then I heard about promises and found that library called Bluebird. Now I wanted to work with nodes child process to get commands running.

What are streams and how to use them

A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout. Streams are readable, writable, or both. All streams are instances of EventEmitter

from Node.js Stream API documentation

So regarding to this, let us say you want to get the content of a file. This you can get easily with the file system API:

var fs = require('fs');

fs.readFile('./README.md', {encoding: 'utf-8'}, function(err, data) {
  if (err) {
    throw err;
  }

  console.log(data);
});

Child Process with promises (Bluebird)

With a child process you can run a command from Node.js. For example you want to list the contents of a directory:

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

var child = spawn('ls', ['-la'], {cwd: './'});

child.stdout.on('data', function(data) {
  console.log('stdout: ' + data);
});

child.stderr.on('data', function(data) {
  console.log('stderr: ' + data);
});

With promises this code would look more like this:

var Promise = require('bluebird');

var prom = new Promise(function(resolve, reject) {
  var spawn = require('child_process').spawn;
  var child = spawn('ls', ['-la'], {cwd: './'});

  spawn.stdout.on('data', resolve);
  spawn.stderr.on('data', reject);
});

prom
  .then(function(data) {
    console.log(data);
  })
  .catch(function(e) {
    console.log('error: ' + e);
  });

So promises are most likely a different style of writing the same thing. Of course there is more. Promises return values and/or throw errors. This way your try-catch code will look more readable, so it will be easier to maintain.

If you want to learn more about promises, I recommend the links on the readme of Bluebird.

Summary

It took me a while to get into streams and promises, but now it looks very handy to me. This post shall stay as a code snippet reminder for me, so that I can get into this topic back again if I was too long running around in a different language. So, if you work with Node.js and you did not do it yet, take a look at promises and try it out yourself.