Design patterns in Node.js for Developers

Design patterns in Node.js for Developers

Design patterns in Node.js for Developers - Design patterns, simply put, are a way for you to structure your solution's code in a way that allows you to gain some kind of benefit. ..

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.


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.

var PI = Math.PI;

function circle (radius) {
  return radius * radius * PI;
} = 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');


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


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() {;

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) {



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){
  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.


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 =;
$ (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

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Hands on with Node.Js Streams | Examples & Approach

The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.

Node JS Complete Course PDF | Node.js

There are some Features that choose Node.js the foremost decision of programming designers.

Using the Node REPL - Node.js Basics [05]

Learn about the Node.js REPL (Read Evaluate Print Loop) and get your hands dirty with Node.js wby running your first Node commands. Java Brains website: http...