Top Node.js Libraries for Web Development with Code Examples

Because of its quick, scalable, and lightweight design, Node.js has completely changed server-side programming. The vast ecosystem of libraries and modules made possible by npm is a primary factor in its success. Node.js libraries can make a big difference in how easy it is to construct REST APIs, real-time applications, and intricate microservices. To get you started, here’s a list of some of the top Node.js libraries, complete with code samples.

Node.js comes with a set of built-in libraries that provide core functionalities. Here’s a list of some of the most commonly used ones:

Core Modules

  • assert: Provides assertion functions for testing conditions.
  • buffer: Creates and manipulates buffers of raw data.
  • child_process: Executes child processes.
  • cluster: Allows multiple Node.js processes to share a single port.
  • console: Provides functions for printing to the console.
  • crypto: Provides cryptographic functionality.
  • dgram: Implements the Datagram API for UDP sockets.
  • dns: Resolves DNS hostnames to IP addresses.
  • domain: Groups related objects together for error handling.
  • events: Implements an event emitter class.
  • fs: Provides functions for working with files and directories.
  • http: Implements the HTTP server and client modules.
  • https: Implements the HTTPS server and client modules.
  • net: Implements the TCP and UDP network protocols.
  • os: Provides information about the operating system.
  • path: Provides utilities for working with file and directory paths.
  • process: Provides information about the Node.js process.
  • querystring: Parses and stringifies URL query strings.
  • readline: Provides an interface for reading data from the command line.
  • stream: Implements the stream API for reading and writing data.
  • timers: Provides functions for setting timers.
  • tls: Implements the TLS/SSL protocol.
  • tty: Provides functions for working with terminals.
  • url: Provides functions for parsing and constructing URLs.
  • util: Provides utility functions for various tasks.
  • v8: Provides access to the V8 JavaScript engine.
  • zlib: Provides functions for compressing and decompressing data.

Top Node.js Libraries

top Node.js libraries

1. Express.js – Web Framework

Express.js is one of the most popular libraries for building web applications and APIs in Node.js. It’s lightweight and flexible, with many plugins available to extend its functionality.

Installation:

npm install express

Example Code:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

2. Mongoose – MongoDB ODM

Mongoose provides a straightforward, schema-based solution for modelling your data with MongoDB. It is great for handling relationships between data, providing query-building capabilities, and managing validations.

Installation:

npm install mongoose

Example Code:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydatabase', {useNewUrlParser: true, useUnifiedTopology: true});

const userSchema = new mongoose.Schema({
  name: String,
  age: Number
});

const User = mongoose.model('User', userSchema);

const newUser = new User({name: 'Jaydip', age: 30});
newUser.save().then(() => console.log('User saved!'));

3. Axios – HTTP Client

Axios is a promise-based HTTP client for Node.js that simplifies making HTTP requests to external APIs and services.

Installation:

npm install axios

Example Code:

const axios = require('axios');

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

4. Lodash – Utility Library

Lodash provides utility functions for common programming tasks, such as working with arrays, objects, numbers, and strings. It makes JavaScript easier by taking the hassle out of working with data.

Installation:

npm install lodash

Example Code:

const _ = require('lodash');

let numbers = [1, 2, 3, 4, 5, 6];
let evens = _.filter(numbers, (n) => n % 2 === 0);
console.log(evens); // Output: [2, 4, 6]

5. Passport.js – Authentication Middleware

Passport.js is a flexible and modular authentication middleware for Node.js. It supports multiple strategies like local authentication, OAuth, and OpenID.

Installation:

npm install passport

Example Code:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) {
    // This is where you would perform authentication with a database
    if (username === 'admin' && password === 'password') {
      return done(null, {username: 'admin'});
    } else {
      return done(null, false, { message: 'Invalid credentials' });
    }
  }
));

// Express setup and routes would go here, using passport to authenticate

6. Socket.io – Real-Time Communication

Socket.io enables real-time bidirectional communication between web clients and servers. It’s used for applications like chat rooms, live updates, and multiplayer games.

Installation:

npm install socket.io

Example Code:

const io = require('socket.io')(3000);

io.on('connection', (socket) => {
  console.log('A user connected');
  
  socket.on('message', (msg) => {
    console.log('Message received:', msg);
    io.emit('message', msg); // Broadcast the message to all users
  });
  
  socket.on('disconnect', () => {
    console.log('A user disconnected');
  });
});

7. Joi – Data Validation

Joi is a data validation library that allows you to describe your data schema and validate it before saving or processing. It’s beneficial for form validation and ensuring the integrity of your data.

Installation:

npm install joi

Example Code:

const Joi = require('joi');

const schema = Joi.object({
  username: Joi.string().min(3).max(30).required(),
  password: Joi.string().min(6).required()
});

const result = schema.validate({ username: 'Jay', password: 'password123' });
if (result.error) {
  console.log('Validation failed:', result.error.details);
} else {
  console.log('Validation passed!');
}

8. Winston – Logging

Winston is a flexible and extensible logging library that helps you record events from your Node.js application, whether for debugging, performance monitoring, or error tracking.

npm install winston
const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'app.log' }),
  ],
});

logger.info('This is an info message');
logger.error('This is an error message');

9. Bcrypt – Password Hashing

Bcrypt is a library used to hash passwords and compare hashed passwords, which is critical for user authentication.

npm install bcrypt
const bcrypt = require('bcrypt');
const saltRounds = 10;

bcrypt.hash('myPassword123', saltRounds, (err, hash) => {
  if (err) throw err;
  
  console.log('Hashed password:', hash);

  bcrypt.compare('myPassword123', hash, (err, result) => {
    console.log('Password match:', result); // Output: true
  });
});

10. Moment.js – Date Manipulation

Moment.js is a popular library for working with dates and times in JavaScript. It provides an easy-to-use API to parse, format, and manipulate dates.

npm install moment
const moment = require('moment');

let now = moment();
console.log(now.format('MMMM Do YYYY, h:mm:ss a')); // Output: current date and time

11. Async.js – Asynchronous Utilities

Async.js provides powerful functions for working with asynchronous JavaScript. It helps manage the control flow, perform async iterations, and handle tasks in parallel or series, making code cleaner and more efficient.

npm install async
const async = require('async');

async.parallel([
  function(callback) {
    setTimeout(() => {
      console.log('Task One');
      callback(null, 'One');
    }, 200);
  },
  function(callback) {
    setTimeout(() => {
      console.log('Task Two');
      callback(null, 'Two');
    }, 100);
  }
], (err, results) => {
  console.log('All tasks completed:', results); // Output: ['One', 'Two']
});

12. Dotenv – Environment Variables Management

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. It simplifies configuration management in your Node.js application.

npm install dotenv
require('dotenv').config();

console.log(process.env.DB_HOST);  // Load and use environment variables

.env file:

DB_HOST=localhost
DB_USER=root
DB_PASS=secret

13. PM2 – Process Manager

PM2 is a production-ready process manager for Node.js applications. It allows you to manage and keep your applications alive forever, reload them without downtime, and monitor them.

npm install pm2 -g
pm2 start app.js   # Start your Node.js application
pm2 list           # List running applications
pm2 logs           # Check application logs

14. Nodemailer – Email Sending

Nodemailer is the go-to module for sending emails in Node.js. It supports a variety of email services, such as Gmail, and SMTP servers, making email functionality seamless.

npm install nodemailer
const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
  }
});

let mailOptions = {
  from: 'youremail@gmail.com',
  to: 'recipient@example.com',
  subject: 'Test Email',
  text: 'Hello, this is a test email from Node.js!'
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    return console.log(error);
  }
  console.log('Email sent: ' + info.response);
});

15. Cheerio – Web Scraping

Cheerio is a fast, flexible, and lean implementation of jQuery designed for server-side web scraping in Node.js. It helps in parsing and manipulating HTML or XML.

npm install cheerio
const cheerio = require('cheerio');
const axios = require('axios');

axios.get('https://example.com').then(response => {
  const $ = cheerio.load(response.data);
  const heading = $('h1').text();
  console.log('Page heading:', heading);
});

16. Morgan – HTTP Request Logger

Morgan is a middleware that logs HTTP requests to your Node.js server, providing essential information for debugging, auditing, and performance tuning.

npm install morgan
const express = require('express');
const morgan = require('morgan');
const app = express();

app.use(morgan('combined'));

app.get('/', (req, res) => {
  res.send('Hello, Morgan logging is enabled!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

17. Chalk – Terminal String Styling

Chalk is a library used to style and colour terminal strings, which is useful for making console outputs easier to read and visually appealing during development or debugging.

npm install chalk
const chalk = require('chalk');

console.log(chalk.green('Success!'));
console.log(chalk.red('Error occurred!'));
console.log(chalk.blue('Informational message.'));

18. Cors – Cross-Origin Resource Sharing

CORS (Cross-Origin Resource Sharing) is a security feature that restricts how resources are shared across different domains. The cors library helps enable CORS in your Express.js applications with just a few lines of code.

npm install cors
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/data', (req, res) => {
  res.json({ msg: 'CORS is enabled!' });
});

app.listen(3000, () => {
  console.log('Server running with CORS enabled on port 3000');
});

19. Jest – Testing Framework

Jest is a delightful JavaScript testing framework with a focus on simplicity. It works well with Node.js for unit testing, especially when working with frameworks like React and Redux.

npm install jest
// sum.js
function sum(a, b) {
  return a + b;
}
module.exports = sum;

// sum.test.js
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});
npm run jest

20. Sequelize – ORM for SQL Databases

Sequelize is a promise-based ORM for Node.js that supports several SQL databases like MySQL, PostgreSQL, SQLite, and MariaDB. It helps in writing queries, defining models, and managing migrations.

npm install sequelize
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');

const User = sequelize.define('User', {
  username: {
    type: DataTypes.STRING,
    allowNull: false
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false
  }
});

sequelize.sync().then(() => {
  return User.create({
    username: 'jaydip',
    password: 'password123'
  });
}).then(user => {
  console.log(user.toJSON());
});

21. UUID – Generate Unique IDs

UUID is a library for generating RFC-compliant Universally Unique Identifiers (UUIDs), which are commonly used in applications to uniquely identify resources, like users or orders.

npm install uuid
const { v4: uuidv4 } = require('uuid');

const userId = uuidv4();
console.log('Generated User ID:', userId);

Conclusion

Node.js’s vibrant library ecosystem allows developers to easily build scalable, efficient, modern applications. From handling real-time data with Socket.io to simplifying data validation with Joi, these libraries provide the building blocks needed for efficient development. Integrating them into your projects will help you save time and effort, allowing you to focus on core features.

These additional Node.js libraries extend the functionality of your applications, covering everything from logging, web scraping, and data management to testing and process management. With these libraries, your Node.js development experience will become smoother, faster, and more productive. Each library solves a specific problem and allows you to focus on building core features while minimizing the hassle of managing lower-level details.

Which Node.js library is your favourite? Let us know in the comments below!

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.