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.
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
Alternate Options
Restify, Hapi, Meteor
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
Alternate Options
pusher
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
Alternate Options
Bunyan
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
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
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
Alternate Options
busboy
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
Alternate Options
envy
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
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
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
Alternatives
Mock.js, json-schema-faker
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
Alternate Options
sendmail, emailjs
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!