Bluebird.js with Child Process2014-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 EventEmitterfrom 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:

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:

With promises this code would look more like this:

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.