Essential NPM modules for Node.js developers – Nov 2015

Whether you’re just coming into it or you’re a seasoned developer, JavaScript development nowadays revolves around Node.js’s amazing package manager, NPM. Utilizing the right modules can be essential to productivity and helps prevent you from re-inventing the wheel. In the past few years the community has truly exploded and without any guidance it can be difficult to initially know what modules are available. But fear not because I’ve compiled a list of ones that I think can benefit almost any JavaScript developer.

lodash

Regardless of whether you’re building a server-side or client-side application lodash is one module that will definitely make your life easier. lodash (which started as a fork of Underscore.js) provides utility functions for working with objects, arrays, and functions.

Here’s a brief example of the kind of operation that lodash simplifies. Say I want to transform an array of numbers by multiplying each one by 2.

In VanillaJS that would look like this.

var numbers = [1, 2, 3];

var result = [];
for (var i = 0, j = numbers.length; i < j; i++) {
  result.push(numbers[i] * 2);
}

console.log(result);
// [2, 4, 6]

Now if we use the map function that lodash provides we can accomplish the same thing by just passing a function that gets evaluated for each number in the array.

var numbers = [1, 2, 3];

var result = _.map(numbers, function (x) {
  return x * 2;
});

console.log(result);
// [2, 4, 6]

That’s just the tip of the iceberg, but spend some a little time using it and you may wonder how you ever lived without it.

express

With the rise of SPA (single page applications), the need to write REST APIs is paramount. But we don’t want to take forever writing boilerplate or learning a complicated framework just to get it going right? Well what if I told you that you can create a REST API in only 8 lines?

var express = require('express');
var app = express();

app.get('/buckets', function (req, res) {
  res.send('There are no buckets here.');
});

app.listen(8080);

With that you can point your browser to http://localhost:8080/buckets and you’ll see the test message returned.

The ability to quickly REST APIs together certainly isn’t unique to express as it can be had in other Python frameworks like bottle.py and flask but it does it so well that I’ve shied away from the latter over the past year.

express is not limited to just building REST APIs though as you can still build applications that use server-side templating akin to what you’d do in a framework like Django or Rails. Whichever way you use it, it’s a timesaver and I absolutely love it.

pm2

If you’re ever planning on deploying a Node.js application in a production environment then you’re going to need pm2. Why? Let’s take a look.

This is how you’d normally fire up an application.

node app.js

So what’s wrong with this approach? Well first off the process isn’t running in the background so you’d have to leave your terminal session open. Also what if the application crashes, who’s going to restart it? What about logging and monitoring?

But fear not, you won’t have to babysit your terminal because pm2 addresses all these issues. It is a process manager for node.js applications. When you run an application with pm2 it will ensure that the process stays running and will attempt to restart it in the event of a failure. In addition pm2 also offers automatic log rotation, process and resource monitoring, and clustering.

sequelize

In a perfect world it would be great to be able to use MongoDB for everything, and that seems to be what a lot Node.js tutorials tend to preach. However, if you’re integrating with existing systems or need ACID compliance then you what you really need is a way to interface with relational databases like MySQL, PostgreSQL, SQLite, and SQL Server.

All the aforementioned relational database engines do have modules for interfacing with them but using these as-is would require you write a lot of boilerplate. The sequelize project emerged to provide a robust object relation mapper (ORM) so that you’re not constantly writing SQL queries within your code.

In a nutshell, sequelize allows you to interact with your data models in a programmatic way that is clear and concise.

Here’s a quick example of how you’d connect to a MySQL database, define a model, and fetch a row by its primary key.

// Setup our database instance
var Sequelize = require('sequelize');
var sequelize = new Sequelize('my_database', 'benhanna', 'password');

// Define a model for an existing table
var Bucket = sequelize.define('Bucket', {
  id: {
    type: Sequelize.STRING,
    primaryKey: true
  },
  name: {
    type: Sequelize.STRING
  }
});

// Fetch a row by the primary key
Bucket
  .findById(1)
  .then(function (bucket) {
    // Log the row that was returned
    console.log(bucket);
  });

And notice I didn’t have to worry about writing any SQL. Of course, this is just the tip of the iceberg as to what sequelize can do but once you’ve experienced it you won’t want to talk to another SQL database without it.