Design patterns in Node.js for Developers

When talking about design patterns you may think of singletons, observers or factories. This article is not exclusively dedicated to them but deals with other common patterns as well, like dependency injection or middlewares.

What are design patterns?

A design pattern is a general, reusable solution to a commonly occurring problem.

Singletons

The singleton patterns restrict the number of instantiations of a “class” to one. Creating singletons in Node.js is pretty straightforward, as require is there to help you.

//area.js
var PI = Math.PI;

function circle (radius) {
  return radius * radius * PI;
}

module.exports.circle = circle;

It does not matter how many times you will require this module in your application; it will only exist as a single instance.

var areaCalc = require('./area');

console.log(areaCalc.circle(5));

Because of this behaviour of require, singletons are probably the most common Node.js design patterns among the modules in NPM.


You may also like: Design patterns in Node.js: a practical guide


Observers

An object** maintains a list of dependents/observers and notifies them** automatically on state changes. To implement the observer pattern, EventEmitter comes to the rescue.

// MyFancyObservable.js
var util = require('util');
var EventEmitter = require('events').EventEmitter;

function MyFancyObservable() {
  EventEmitter.call(this);
}

util.inherits(MyFancyObservable, EventEmitter);

This is it; we just made an observable object! To make it useful, let’s add some functionality to it.

MyFancyObservable.prototype.hello = function (name) {
  this.emit('hello', name);
};

Great, now our observable can emit event - let’s try it out!

var MyFancyObservable = require('MyFancyObservable');
var observable = new MyFancyObservable();

observable.on('hello', function (name) {
  console.log(name);
});

observable.hello('john');

Factories

The factory pattern is a creational pattern that doesn’t require us to use a constructor but provides a generic interface for creating objects. This pattern can be really useful when the creation process is complex.

function MyClass (options) {
  this.options = options;
}

function create(options) {
  // modify the options here if you want
  return new MyClass(options);
}

module.exports.create = create;

Factories also make testing easier, as you can inject the modules dependencies using this pattern.

Dependency Injection

Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, into a dependent object.

In this example, we are going to create a UserModel which gets a database dependency.

function userModel (options) {
  var db;
  
  if (!options.db) {
    throw new Error('Options.db is required');
  }
  
  db = options.db;
  
  return {
    create: function (done) {
      db.query('INSERT ...', done);
    }
  }
}
 
module.exports = userModel;

Now we can create an instance from it using:

var db = require('./db');

var userModel = require('User')({
  db: db
});

Why is it helpful? It makes testing a lot easier - when you write your unit tests, you can easily inject a fake db instance into the model.

Middlewares / pipelines

Middlewares are a powerful yet simple concept: the output of one unit/function is the input for the next. If you ever used Express or Koa then you already used this concept.

It worths checking out how Koa does it:

app.use = function(fn){
  this.middleware.push(fn);
  return this;
};

So basically when you add a middleware it just gets pushed into a middleware array. So far so good, but what happens when a request hits the server?

var i = middleware.length;
while (i--) {
  next = middleware[i].call(this, next);
}

No magic - your middlewares get called one after the other.

Streams

You can think of streams as special pipelines. They are better at processing bigger amounts of flowing data, even if they are bytes, not objects.

process.stdin.on('readable', function () {
    var buf = process.stdin.read(3);
    console.dir(buf);
    process.stdin.read(0);
});
$ (echo abc; sleep 1; echo def; sleep 1; echo ghi) | node consume2.js 
<Buffer 61 62 63>
<Buffer 0a 64 65>
<Buffer 66 0a 67>
<Buffer 68 69 0a>

Further reading

PM2 tutorial for Node.js developers

A Beginner’s Guide to npm: The Node Package Manager

#node-js #javascript

Design patterns in Node.js for Developers
5 Likes328.20 GEEK