Node.js is its rich package ecosystem, which includes a wide variety of packages and modules that can be easily integrated into your application.

Important Nodejs packages
Node.js is a popular open-source platform that is widely used for building scalable and high-performance applications. With the help of Node.js, developers can build server-side applications using JavaScript, which makes it easier for them to create web applications, APIs, and microservices.
One of the key strengths of Node.js is its rich package ecosystem, which includes a wide variety of packages and modules that can be easily integrated into your application. In this article, we will take a look at some of the most useful packages in Node.js, along with examples of how to use them.
1. Express.js
Express.js is a popular Node.js web application framework that provides a simple, yet powerful way to build web applications and APIs. It provides a robust set of features, including routing, middleware support, and templating engines. Here’s an example of how to create a simple web server using Express.js:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
In this example, we create an Express.js application and define a route for the root path (“/”). When a GET request is made to this route, the server sends the response “Hello World!”.
2. Socket.IO
Socket.IO is a real-time web socket library that enables bidirectional communication between the server and the client. It provides a simple and easy-to-use API for sending and receiving messages in real-time. Here’s an example of how to use Socket.IO:
npm install socket.io
indes.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
In this example, we create a simple chat application using Socket.IO. When a user connects to the server, we log a message to the console. When the user sends a message, we log it to the console and emit the message to all connected clients.
3. Mongoose
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a simple and easy-to-use API for defining schemas and models, as well as querying and manipulating data in MongoDB. Here’s an example of how to use Mongoose:
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/test', { userNewUrlParser: true})
.then(() => console.log('Connected!'));
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});
const User = mongoose.model('User', userSchema);
const newUser = new User({ name: "Ko Ko", email: "[email protected]"});
newUser.save((err, user) => {
if (err) return console.error(err);
console.log('User saved successfully', user);
});
In this example, we define a schema for a user and create a new user object. We then save the user object to the MongoDB database using the `save()` method.
4. Nodemailer
Nodemailer is a Node.js module for sending emails. It provides a simple and easy-to-use API for sending emails using SMTP, sendmail, or Amazon SES. Here’s an example of how you can use Nodemailer to send an email using Gmail as the SMTP provider:
const nodemailer = require("nodemailer");
const transporter = nodemailer.createTransport({
host: "smtp.forwardemail.net",
port: 465,
secure: true,
auth: {
// TODO: replace `user` and `pass` values from <https://forwardemail.net>
user: "[email protected]",
pass: "REPLACE-WITH-YOUR-GENERATED-PASSWORD",
},
});
// async..await is not allowed in global scope, must use a wrapper
async function main() {
// send mail with defined transport object
const info = await transporter.sendMail({
from: '"Fred Foo 👻" <[email protected]>', // sender address
to: "[email protected], [email protected]", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>", // html body
});
console.log("Message sent: %s", info.messageId);
// Message sent: <[email protected]>
//
// NOTE: You can go to https://forwardemail.net/my-account/emails to see your email delivery status and preview
// Or you can use the "preview-email" npm package to preview emails locally in browsers and iOS Simulator
// <https://github.com/forwardemail/preview-email>
//
}
main().catch(console.error);
In the example above, Nodemailer is used to create a reusable transporter object with the Gmail SMTP credentials. Then, an email is composed using both plain text and HTML body, with the email’s sender, recipient, subject, and content all defined in the mailOptions
object. Finally, the email is sent using the sendMail
method of the transporter object. If an error occurs during the process, it will be logged to the console. Otherwise, a message containing the ID of the sent email will be logged.
5. Body-Parser
body-parser is a middleware for parsing the incoming request body in a Node.js web application. It allows you to access the contents of a POST, PUT, or DELETE request in the `req.body` property of the request object.
Here is an example of how to use `body-parser` in an Express.js web application:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
res.send('welcome, ' + req.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
// create user in req.body
})
In the example above, we first require the `body-parser` module and then create an instance of the `express` application. We then add the middleware to parse `application/x-www-form-urlencoded` and `application/json` requests. Finally, we define a route for handling POST requests to `/api/users` and log the `req.body` object to the console.
When a POST request is sent to the server, `body-parser` will parse the request body and populate the `req.body` property with an object containing the key-value pairs of the submitted data. The contents of `req.body` will depend on the format of the request body, which can be either `application/x-www-form-urlencoded` or `application/json`.
For example, if the request body is:
{
"name" : "Ko Aung",
"age" : 30
}
then `req.body` will be an object with the following properties:
{
"name" : "Ko Aung",
"age" : 30
}
Overall, `body-parser` is a useful middleware for processing incoming requests with body data in Node.js web applications.
6. Request
In Node.js, a request refers to a client-side HTTP request that is sent to a server for processing. The server responds to the request with an appropriate HTTP response.
Here is an example of sending a request in Node.js using the built-in `http` module:
const http = require('http');
http.get('http://example.com/api', (response) => {
console.log("Response status code: ${response.status}");
response.on('data', (data) => {
console.log('Response body: ' + JSON.stringify(data));
});
});
In this example, the `http.get` method is used to send an HTTP GET request to `http://example.com`. The callback function handles the response by logging the status code and data to the console.
Another example using the popular `axios` library:
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('http://example.com/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
Here, the `axios.get` method is used to send an HTTP GET request to `http://example.com`. The `.then` method is used to handle the successful response, and the `.catch` method is used to handle any errors that may occur. The response status code and data are logged to the console.
7. Passport
A passport is a popular authentication middleware for Node.js web applications. It provides a simple and flexible way to handle user authentication, authorization, and session management. Passport supports various authentication strategies, such as local authentication, OAuth, OpenID, and many more.
Here’s an example of how to use Passport in a Node.js application with the local authentication strategy:
1. Install Passport and the passport-local strategy using npm:
npm install passport passport-local
2. Require the necessary modules in your application:
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
3. Define the local authentication 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.verifiedPassword(password)){
return done(null, false);
}
return done(null, user);
})
}
});
4. Configure Passport to serialize and deserialize user objects:
passport.serializeUser(function(user, done){
done(null, user.id);
});
passport.deserializeUser(function(id, done){
User.findById(id, function(err, user){
done(err, user);
});
}
5. Initialize Passport and add it as middleware to your application:
app.use(passport.initialize());
app.use(passport.session());
6. Implement the login route to authenticate the user:
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login'}),
function(req, res){
res.redirect('/');
});
In this example, we use the passport-local strategy to authenticate the user based on their username and password. We also serialize and deserialize the user object to maintain their session across requests.
Once configured, Passport provides a powerful and easy-to-use authentication system for your Node.js application.
7. Async
In Node.js, “async” refers to writing code in an asynchronous, non-blocking way. This allows your program to continue executing while waiting for I/O operations to complete, rather than blocking until they finish.
Here’s an example of using async/await to perform a database query in Node.js:
const mysql = require('mysql2/promise');
async function getUsers(){
console connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test.db'
});
const [ rows, fields ] = await connection.query("SELECT * FrOM users");
console.log(rows);
connection.end();
}
getUsers();
In the above example, the `mysql2` package is used to create a database connection and perform a query. The `async` function `getUsers` is defined with `await` used to wait for the results of the query before logging the returned rows and ending the connection.
Another example using the Node.js `fs` (file system) module to read a file asynchronously:
const fs = require('fs');
async function readFileAsync(){
try {
const data = await fs.promises.readFile('/path/to/file', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFileAsync();
In this example, `fs.promises.readFile` is used to read a file asynchronously with `await`, and the returned data is logged to the console. Any errors are caught and logged to the console as well.
In conclusion, NodeJS offers a lot of frameworks to make your web application stand out and this makes NodeJS one of the best back-end technologies.
Ref : Important Nodejs packages in 2023

#HIRE ME
Ko Aung Thu Oo
Having over 15 years of working experience in Laravel, PHP, Flutter, Node.Js, Vue.JS, JAVA. Strong information technology professional with a degree i...
View detail