Most Useful NodeJS Libraries a Nodejs Developer Should Know

    Jun 07, 2020       by Pankaj Kumar
most-useful-nodejs-libraries-a-nodejs-developer-should-know.jpg

Ryan Dahl and other developers, at  Joyent, created Node.js. Node.js is a runtime environment that allows us to write a server-side application using JavaScript. Now a day, Node.js is one of the most preferred technology for creating application backend. And due to the popularity of Node.js, a complete web application can be developed using Javascript.

Due to the popularity of Node.js many freshers starting their career in IT with Node.js. So in this article we will see the most useful libraries of Nodejs a fresher Node.js developer should know.

Most Useful NodeJS Libraries

 

1. Express

Express is a fast, unopinionated minimalist web framework for Node.js. 

 

const express = require('express')

const app = express()

app.get('/', function (req, res) {

  res.send('Hello World')

})

app.listen(3000)

 

Advantages

  • It makes Node.js web application development fast and easy.
  • Easy to configure and customize as per the requirement.
  • GET, PUT, POST, and DELETE requests can be handled easily
  • Preferred for all type of web application(Single Page, Multi Page, Mobile Application)

Alternate Options

Restify, Hapi, Meteor

 

2. socket.io

It is a library for realtime web applications. It enables realtime, bi-directional communication between web clients and servers.

io.on('connection', socket => {

  socket.emit('request', /* … */); // emit an event to the socket

  io.emit('broadcast', /* … */); // emit an event to all connected sockets

  socket.on('reply', () => { /* … */ }); // listen to the event

});

 

Advantages

  • Useful for bi-directional streaming, instant messaging, and document collaboration.
  • Socket.IO APIs are built to be easier to work with

Alternate Options

pusher

 

3. morgan

HTTP request logger middleware for node.js

 

morgan (':method :url :status :res[content-length] - :response-time ms')---

const express = require('express')

const morgan = require('morgan')

const app = express()

app.use(morgan('combined'))

app.get('/', function (req, res) {

  res.send('hello, world!')

})

 

Advantages

  • most preferred for logging the requests in console, file, database

Alternate Options

Bunyan

 

4. body-parser

It is a Node.js body parsing middleware.

Parse incoming request bodies in a middleware before the handlers, available under the req.body property.

 

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

 

Advantages

  • Very easy to use for all type of input request

 

5. Passport

Passport is Express-compatible authentication middleware for Node.js. It's sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies.

Passport uses the concept of strategies to authenticate requests. Let's have a look on the below strategy.

passport.use(new LocalStrategy(

  function(username, password, done) {

    User.findOne({ username: username }, function (err, user) {

      if (err) { return done(err); }

      if (!user) { return done(null, false); }

      if (!user.verifyPassword(password)) { return done(null, false); }

      return done(null, user);

    });

  }

));

 

There are 480+ strategies. Find the ones you want at passportjs.org

Advantages

  • Single sign-on with OpenID and OAuth

  • Easily handle success and failure

  • Supports persistent sessions

  • Lightweight code base

 

Alternate Options

Auth0, OAuth2, Amazon Cognito

 

6. multer

It is a node.js middleware for handling multipart/form-data, which is mainly used for uploading files

<form action="/profile" method="post" enctype="multipart/form-data">

  <input type="file" name="avatar" />

</form>

 

var express = require('express')

var multer  = require('multer')

var upload = multer({ dest: 'uploads/' })

 

var app = express()

 

app.post('/profile', upload.single('avatar'), function (req, res, next) {

  // req.file is the `avatar` file

  // req.body will hold the text fields, if there were any

})

 

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {

  // req.files is array of `photos` files

  // req.body will contain the text fields, if there were any

})

 

var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])

app.post('/cool-profile', cpUpload, function (req, res, next) {

  ....

})

 

Advantages

  • Super Easy to upload multipart/form-data files
  • name of the file/storage can easily be adjusted for different files as per the requirement

Alternate Options

busboy

 

7. dotenv

It is a zero-dependency module that loads environment variables from a .env file into process.env.

require('dotenv').config()

const db = require('db')

db.connect({

  host: process.env.DB_HOST,

  username: process.env.DB_USER,

  password: process.env.DB_PASS

})

// .env file

DB_HOST=localhost

DB_USER=rootDB_PASS=pass@123

 

Advantages

  • Loads environment variable like DB connection, hostname, secret keys
  • separate the configuration from code which makes super easy to manage code at different server.

Alternate Options

envy

 

8. CORS

It is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

var express = require('express')

var cors = require('cors')

var app = express()

 

app.use(cors())

 

app.get('/products/:id', function (req, res, next) {

  res.json({msg: 'This is CORS-enabled for all origins!'})

})

 

app.listen(80, function () {

  console.log('CORS-enabled web server listening on port 80')

})

 

Advantages

  • Resolved all CORS related issue with few line of code

 

9. sequelize

 

It is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

 

const sequelize = new Sequelize
('database', 'username', 'password',
{
host: 'localhost',
dialect: /* one of 'mysql'
| 'mariadb' | 'postgres' | 'mssql' */ });

 

Advantages

  • Very easy to connect mysql database

 

10. faker

Generate massive amounts of dummy data for testing purposes in the browser and node.js.

const faker = require('faker');

const randomName = faker.name.findName(); // Rowan Nikolaus

const randomEmail = faker.internet.email(); // Kassandra.Haley@erich.biz

const randomCard = faker.helpers.createCard(); // random contact card containing many properties

 

Advantages

  • Quick and easy to use
  • contains a super useful generator methods

Alternatives

Mock.js, json-schema-faker

 

11. nodemailer

Most preferred package in Node.js to send emails.

const nodemailer = require("nodemailer");

let testAccount = await nodemailer.createTestAccount();

let transporter = nodemailer.createTransport({

  host: "smtp.ethereal.email",

  port: 587,

  secure: false,

  auth: {

    user: testAccount.user,

    pass: testAccount.pass

  }

});

let info = await transporter.sendMail({

  from: '"Fred Foo " <foo@example.com>',

  to: "bar@example.com, baz@example.com",

  subject: "Hello ",

  text: "Hello world",

  html: "<b>Hello world</b>"

});

 

Advantage

  • send emails using SMTP easily

Alternate Options

sendmail, emailjs

 

Conclusion

Node.js is one of the most demanding JavaScript frameworks today and any fresher can start working on it if they are having basic knowledge of any programming language.

Click here to find much more content available on this platform for beginner Node.js developer. You can also find other demos of Other Sample Application here to start working on enterprise-level applications.

Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thanks!


WHAT'S NEW

Find other similar Articles here: