Nodejs json web token

JWT is used to secure web token. JWT stands for JSON Web token.
JWT is used to encrypt the token so that no one hacks the token.

How to install JSON Web Token in Nodejs?


npm i jsonwebtoken

How to create JSON Web Token token in Nodejs?

Suppose, you create createjwt.js file
include jsonwebtoken through require method


var jwt = require('jsonwebtoken');
module.exports.create_jwt_token= async ()=>{
let role=1;
let email='john@abc.com'
let token = jwt.sign({role:role,email:email}, 'sh233444hh'); // save token into database
console.log("token:-",token);
}

Now, create the index.js file and include the createjwt.js file


var createjwt = require('./createjwt');
createjwt.create_jwt_token();
Output:-
token:- eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoxLCJlbWFpbCI6ImpvaG5AYWJjLmNvbSIsImlhdCI6MTYxMDE3MTk2N30.IGVdnytBjesv4PZld7TZuwqzfGoxL9DOYKK72QfoD0U

How to verify JWT token in Nodejs?

Suppose, you create verifyjwt.js file
include jsonwebtoken through require method


module.exports.verify_jwt_token= async (token)=>{
 
  jwt.verify(token, 'sh233444hh', async function(err, results) {
  if(err){

    console.log("error+++",err);

  }else{

    console.log(results);

  }

  })
  }

Now, create the index.js file and include the verifyjwt.js file


var verifyjwt = require('./verifyjwt');
var token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoxLCJlbWFpbCI6ImpvaG5AYWJjLmNvbSIsImlhdCI6MTYxMDE3MTk2N30.IGVdnytBjesv4PZld7TZuwqzfGoxL9DOYKK72QfoD0U";
var output=verifyjwt.verify_jwt_token(token);
console.log(output);
Output:-
{ role: 1, email: ‘john@abc.com’, iat: 1610173305 }

Nodejs Module

Nodejs Module is like a set of libraries. There are two types of Module
1) Package Module
2) Custom Module

1) Package Module:- This type of module is already created by the NPM community and you can use this.

Step1:- Firstly installed the package
Example:- You want to install http module then write below command


npm install http --save

Step2:- Now, create the index.js file and include the module through require method.


var http = require('http');
const httpServer = http.createServer(app);
httpServer.listen(4444,() => {
 console.log('HTTP Server running on port 4444');
});

2) Custom Module:- You can create your own module.

Suppose, you create a register.js file and write the signup method


module.exports.signup= async ()=>{

// logic implement in this
console.log("signup module is called");

}

Now, create the index.js file and include the register.js file through require method and call the signup method.


var register = require('register');
var data=register.signup();
console.log(data);
Output:-
signup module is called

How to call one file method into another file?

If you want to call one file method into another file then you must define the method through module.exports

Example:- Suppose, You create a file user_info.js and define the method user_details()


module.exports.user_details = async () => {

  var udetails={

    name:"John",
    age:35

  }
  console.log(udetails);
}

Now, create the index.js file and call the user_details method.


var user_info= require('./user_info');
user_info.user_details()
Output:-
{ name: ‘John’, age: 35 }

If you do not define the module.exports

You create a file user_info.js and define the method user_details()


user_details = async () => {

  var udetails={

    name:"John",
    age:35

  }
  console.log(udetails);
}

Now, create the index.js file and call the user_details method.


var user_info= require('./user_info');
user_info.user_details()
Output:-
TypeError: user_info.user_details is not a function

Nodejs bcrypt

Nodejs bcrypt is used to store the password in an encrypted format with hash and salt.

How to install bcrypt package in Nodejs?

Firstly installed bcrypt package through below command.


npm install --save bcrypt

How to generate password in encrypted format through bcrypt?

Bcrypt is used to generated secure passwords.

Suppose, You create generate_hash_password.js file and write the below code.


const bcrypt = require('bcrypt');
var password="Hello123"
const saltRounds = 10;  //write number
var hash_password = bcrypt.hashSync(password, saltRounds); //Password must be save into database
console.log("Hash Password:-",hash_password);
Output:-
Hash Password:-$2b$10$jgXSMwBDsysCirC5xMGYwue0kv7Q00H9.pGBcag6Awrkeb1Pu2o6.

Note:- firstly include bcrypt package through require method after that write the hashSync method of bcrypt.

How to compare encrypted password?

Firstly create the compare_password.js file and write the below code.


const bcrypt = require('bcrypt');
const saltRounds = 10;
var password='Hello123';
var hash_password = '$2b$10$jgXSMwBDsysCirC5xMGYwue0kv7Q00H9.pGBcag6Awrkeb1Pu2o6.'; //which is coming from database 
let encrypt_pwd = hash_password;
let check_password = bcrypt.compareSync(password, encrypt_pwd);
console.log("Password is:-",check_password);

Note:- compareSync method has two parameters
1) raw password
2) encrypted password

Output:-
Password is:-true

Nodejs email

To send the email in Nodejs through nodemailer package.
Firstly installed nodemailer package.


npm install --save nodemailer

Now open the URL https://mailtrap.io/

create the signup

get the username and password

Now, create the email.js file and write the below code


var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  host: 'smtp.mailtrap.io',
  port: 2525,
  auth: {
     user: 'put_your_username_here', //put_your_username_here
     pass: 'put_your_password_here' //put_your_password_here
  }
});

var mailOptions = {
  from: 'fromemail@abc.com',
  to: 'toemail@abc.com',
  subject: 'Test Email',
  html: '

HTML body text data

' }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } });
Output:-
Email sent: 250 2.0.0 Ok: queued

Check the send email content in mailtrap inbox

Nodejs Mysql insert query

to create the MySQL insert query in Nodejs, I have defined 2 steps

Insert Single Record into the table

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the insert.js file and include the connection.js file and write the insert query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('insert into users(name,age) values(?,?)',['John',35], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the insert.js file.


node insert.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 1,
serverStatus: 2,
warningCount: 0,
message: ”,
protocol41: true,
changedRows: 0 }

IN this file, I have created an insert query to save records in the users table.

Now, get the results from the table


select * from users
ID
Name
Age
1
John
35

Insert Multiple Records into the table

Step:2) Now, create the insert.js file and include the connection.js file and write the insert query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('insert into users(name,age) values ?',[[['Rom',31],['Mathew',32],['Sachin',38]]], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the insert.js file.


node insert.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 3,
insertId: 2,
serverStatus: 2,
warningCount: 0,
message: ‘&Records: 3 Duplicates: 0 Warnings: 0’,
protocol41: true,
changedRows: 0 }

Now, get the results from the table


select * from users
Output:-
ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Nodejs Mysql update query

to create the MySQL update query in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Now you want to change user name from John to Sunny and age from 35 to 31 which has userid 1.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the update.js file and include the connection.js file and write the update query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('update users SET name=?,age=? where id=?',['Sunny',31,1], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the update.js file.


node update.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: ‘(Rows matched: 1 Changed: 1 Warnings: 0’,
protocol41: true,
changedRows: 1 }

Now, get the records from the users table.


Select * from users
Output:-
ID
Name
Age
1
Sunny
31
2
Rom
31
3
Mathew
32
4
Sachin
38

Nodejs Mysql delete query

to create the MySQL delete query in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Now you want to delete user which has user id is 1

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the delete.js file and include the connection.js file and write the delete query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('delete from users where id=?',[1], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the delete.js file.


node delete.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: ”,
protocol41: true,
changedRows: 0 }

Now, get the users records from the table.


Select * from users
Output:-
ID
Name
Age
2
Rom
31
3
Mathew
32
4
Sachin
38

Node Mysql select query

to create the MySQL select query in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 1, name: ‘John’, age: 35 },
RowDataPacket { id: 2, name: ‘Rom’, age: 31 },
RowDataPacket { id: 3, name: ‘Mathew’, age: 32 },
RowDataPacket { id: 4, name: ‘Sachin’, age: 38 } ]

Nodejs Mysql select query with where condition

to create the MySQL select query with where condition in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Now, you want to get the user details which has age 35.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users where age=?',[35], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 1, name: ‘John’, age: 35 } ]

Nodejs Mysql Order By

to create the MySQL select query with Order By clause in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Now, You want to get the user details based on age in ascending order.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users Order By age', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 2, name: ‘Rom’, age: 31 },
RowDataPacket { id: 3, name: ‘Mathew’, age: 32 },
RowDataPacket { id: 1, name: ‘John’, age: 35 },
RowDataPacket { id: 4, name: ‘Sachin’, age: 38 } ]

Now, You want to get the user details based on age in descending order so change the query in Step2

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users Order By age DESC', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 4, name: ‘Sachin’, age: 38 },
RowDataPacket { id: 1, name: ‘John’, age: 35 },
RowDataPacket { id: 3, name: ‘Mathew’, age: 32 },
RowDataPacket { id: 2, name: ‘Rom’, age: 31 } ]

Nodejs Mysql Limit

MySql Limit is used to get the number of records from the table as your requirements.
to create the MySQL select query with a Limit clause in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Suppose, You want to get the user details based on limit 1.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users limit 1', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 1, name: ‘John’, age: 35 } ]

Nodejs Mysql create table

to create the table in MySQL, I have defined 2 steps.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the createtable.js file and include the connection.js file and write the query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('CREATE TABLE IF not exists users1 (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,name VARCHAR(50) NOT NULL,age INT(2) NOT NULL', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the createtable.js file.


node createtable.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: ”,
protocol41: true,
changedRows: 0 }

Nodejs MongoDB create collection

MongoDB’s collection is like a table in RDBMS. to create the collection through createCollection() method.

Firstly create the create_collection.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.createCollection("users", function(err, res) {
      if (err) throw err;
       console.log("Collection is created");
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the create_collection.js file.


node create_collection.js
Output:-
Collection is created

Note:- If you have not collection then you create a document then it will check collection is exists or not it does not exists then it will create the collection.

Nodejs MongoDB Drop Collection

MongoDB’s collection is like a table in RDMS. if you want to drop the collection then use dropCollection() method

Firstly create the drop_collection.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.dropCollection("users", function(err, res) {
      if (err) throw err;
       console.log("Collection is removed");
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the drop_collection.js file.


node drop_collection.js
Output:-
Collection is removed

Now, you can check collection is removed or not in MongoDB through command


> show collections

Nodejs MongoDB insert document

MongoDB’s document is like a table’s row in RDBMS. to insert document into the collection through insertOne() or insertMany() method.

Insert one document through insertOne() method

Firstly create the insert_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var user_obj={name:"John",age:35}
     dbo.collection("users").insertOne(user_obj, function(err, res) {
      if (err) throw err;
       console.log("1 document is added into collection");
       console.log(res.ops);
       console.log(res.insertedCount);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the insert_document.js file.


node insert_document.js
Output:-
1 document is added into collection
[ { name: ‘John’, age: 35, _id: 5fdc9e76304b8b785feb4ebf } ]
1

Insert multiple documents through insertMany() method

Firstly create the insert_documents.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
    if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var user_obj=[{name:"Rom",age:31},{name:"Mathew",age:32},{name:"Sachin",age:38}];
     dbo.collection("users").insertMany(user_obj, function(err, res) {
      if (err) throw err;
       console.log("documents are added into collection");
       console.log(res.ops);
       console.log(res.insertedCount);

       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the insert_documents.js file.


node insert_documents.js
Output:-
documents are added into collection
[ { name: ‘Rom’, age: 31, _id: 5fdcdb87b6dad382104b0f86 },
{ name: ‘Mathew’, age: 32, _id: 5fdcdb87b6dad382104b0f87 },
{ name: ‘Sachin’, age: 38, _id: 5fdcdb87b6dad382104b0f88 } ]
3

Nodejs MongoDB update document

MongoDB’s document is like a table’s row in RDBMS. to update document into the collection through updateOne() or updateMany() method.

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

Update one document through updateOne() method

Firstly create the update_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var new_values={$set:{age:40}};
     var where_condition={name:"John"}
     dbo.collection("users").updateOne(where_condition,new_values, function(err, res) {
      if (err) throw err;
       console.log("1 document updated successfully");
       //console.log(res);
       console.log(res.result);
       console.log(res.modifiedCount);

       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the update_document.js file.


node update_document.js
Output:-
1 document updated successfully
{ n: 1, nModified: 1, ok: 1 }
1

Update multiple documents through updateMany() method

Firstly create the update_documents.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
   if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var new_values={$set:{age:45}};
     var where_condition={name:/o/}
     dbo.collection("users").updateMany(where_condition,new_values, function(err, res) {
      if (err) throw err;
       console.log("documents updated successfully");
       //console.log(res);
       console.log(res.result);
       console.log(res.modifiedCount);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the update_documents.js file.


node update_documents.js
Output:-
documents updated successfully
{ n: 2, nModified: 2, ok: 1 }
2

Nodejs MongoDB delete document

MongoDB’s document is like a table’s row in RDBMS. to delete document from the collection through deleteOne() or deleteMany() method.

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

delete one document through deleteOne() method

Firstly create the delete_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var where_condition={name:'Mathew'}
     dbo.collection("users").deleteOne(where_condition, function(err, res) {
      if (err) throw err;
       console.log("1 document deleted successfully");
       console.log("result:",res.result);
       console.log("deleted_count:",res.deletedCount);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the delete_document.js file.


node delete_document.js
Output:-
1 document deleted successfully
result: { n: 1, ok: 1 }
deleted_count: 1

delete multiple documents through deleteMany() method

Firstly create the delete_documents.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
   if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var where_condition={name:/o/}
     dbo.collection("users").deleteMany(where_condition, function(err, res) {
      if (err) throw err;
       console.log("documents deleted successfully");
       //console.log(res);
       console.log("result:",res.result);
       console.log("deleted_count:",res.deletedCount);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the delete_documents.js file.


node delete_documents.js
Output:-
documents deleted successfully
result: { n: 3, ok: 1 }
deleted_count: 3

Nodejs MongoDB find

MongoDB’s document is like a table’s row in RDBMS. to get the documents from the collection through find() or findOne() method.

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

get all the documents through find() method

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).toArray(function(err, res){
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 },
{ _id: 5fddc8f7329e1da50a4ec727, name: ‘Mathew’, age: 32 },
{ _id: 5fddc8f7329e1da50a4ec728, name: ‘Sachin’, age: 38 } ]

Get the specific key value through projection

If you need a specific key-value then use {keyname:1} through projection


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({},{projection:{name:1}}).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’ },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’ },
{ _id: 5fddc8f7329e1da50a4ec727, name: ‘Mathew’ },
{ _id: 5fddc8f7329e1da50a4ec728, name: ‘Sachin’ } ]

if you do not want _id value in the getting results

If you do not need a specific key-value then use {keyname:0} through projection


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({},{projection:{name:1,_id:0}}).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { name: ‘John’ },
{ name: ‘Rom’ },
{ name: ‘Mathew’ },
{ name: ‘Sachin’ } ]

get one document through findOne() method

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").findOne({}, function(err, res) {
      if (err) throw err;
       console.log("1 document show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
1 document show successfully
result: { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 }

Note:- where_condition is used in the first parameter of the find() or findOne() method.
projection is used in the second parameter of the find() or findOne() method.

Nodejs MongoDB sort

sort() method is used along with the find() method in MongoDB in ascending order or descending order based on keyname (field name).

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

get all the documents in ascending order through {keyname:1} in sort() method

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).sort({name:1}).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 },
{ _id: 5fddc8f7329e1da50a4ec727, name: ‘Mathew’, age: 32 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 },
{ _id: 5fddc8f7329e1da50a4ec728, name: ‘Sachin’, age: 38 } ]

get all the documents in descending order through {keyname:-1} in sort() method

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).sort({name:-1}).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec728, name: ‘Sachin’, age: 38 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 },
{ _id: 5fddc8f7329e1da50a4ec727, name: ‘Mathew’, age: 32 },
{ _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 } ]

Nodejs MongoDB limit

limit() method is used to get the number of documents in MongoDB.
limit() method works along with the find() method.

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).limit(2).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 } ]

Nodejs MongoDB join

lookup() method is used between 2 or more collections for join in MongoDB. lookup() method used in the aggregate() method.

Suppose you have 2 collections departments and employees

departments collections


[
  { _id: 1, name: "Engineer", status: 1 },
  { _id: 2, name: "Manager", status: 1 },
  { _id: 3, name: "Peon", status: 1 }
]

employees collections


[
  { _id: 1, name: "John", department_id: 1 }
]

Now, get the employee’s details with the department name.

create the collections_join.js file


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("employees").aggregate([
      { $lookup:
         {
           from: 'departments',
           localField: 'department_id',
           foreignField: '_id',
           as: 'departments_details'
         }
       }
      ]).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log(JSON.stringify(res));
       connection_obj.close();
    });
  }catch(err){

    console.log("connection fails");
  
  }

Now, run the collections_join.js file.


node collections_join.js
Output:-
documents show successfully
result: [{“_id”:1,”name”:”John”,”department_id”:1,”departments_details”:[{“_id”:1,”name”:”Engineer”,”status”:1}]}]

Nodejs Interview Questions

Q1: What is Event Loop?

An event loop is just like a while loop. It executes one command at a time and it will run until Node has executed every line of code. It has
One Process
One Thread
One Event Loop
readmore..

Q2: Difference between setImmediate(), setInterval() and setTimeout()

setImmidate():- this function will execute code at the end of the current event loop cycle. setImmediate() will execute after any I/O operations in the current event loop and before any timers scheduled (setInterval(), setTimeout()) for the next event loop.

setInterval():- this function is used to repeat the execution of your code block at specified intervals.
setInterval(callback, milisecond);

setTimeout():- this function is called when delay time has finished. it is not executed immediately.
[php]
console.log("Hello");
let data=()=>{
console.log("Hi");
}

setTimeout(() => {
console.log(‘set Timeout Call’);
}, 0);

setImmediate(()=>{

console.log("set Immediate Call")

})

process.nextTick(()=>{

console.log(‘next Tick call’);

})
data();
console.log("Bye");
[/php]

Output:- Hello
Bye
Hi
next Tick call
set Immediate Call
set Timeout Call

Q3: What is Callback()?

A function pass as a argument to another function is called callback function. In Nodejs Asynchronous operation is handled by callback function. readmore..

Q4: What is Promise?

The promise is used to handle async operation and it’s resulting value will be success or failure.
A Promise has basically three-state.
1) pending
2) fulfilled
3) rejected
readmore..

Q5: What is REPL?

REPL stands for Read Eval Print Loop. It basically represents a computer environment like Linux/Unix terminal, window console, etc.
readmore..

Q6: How will you debug an application in Node.js?

[php]
node –inspect filename(index.js)
[/php]

Q7: What is package.json?

package.json file contain all npm packages which is used in the project. it is in project root folder. this has various metadata information relevant to the project like project name, version, description, package information.

Q8: How to include module in Nodejs?

to include module in nodejs through require() method with the name of the module.
[php]
var http = require(‘http’);
[/php]

Q9: What is the use export in Nodejs?

exports keyword is used to make properties and methods available outside the module file.

Q10: What is Express?

Express is a Nodejs Framework.

Q11: What is Authorization?

Authorization is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.

Q12: What is stream?

The stream has the most important role in Nodejs. A stream is an object and basically use to handle a large amount of data. Stream workflow “read from input and write to output in sequentially manner” readmore…

Q13: What is EventEmitter?

Nodejs follow Event-Driven based architecture so every action is an event in Nodejs like open the file to read is an event.
In Nodejs to use Event Emitter firstly include event module in the code.

[php]
var events = require(‘events’);
[/php]

after that create the object through a new keyword.

[php]
var eventEmitter = new events.EventEmitter();
[/php]
readmore…

Q14: Explain the concept of middleware in Node.js?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle.

Q15: What is Asynq await?

await function is used to return the Promise. But the function async needs to be declared before awaiting a function returning a Promise.

Q16: Explain Generators?

Generators is a function that is used for lazy execution. it is used to execution suspended and resumed at a later point.
Generators have two methods
1) yield method
2) next method
readmore…

Q17: What is Nodejs?

Ans:- Node.js is an open-source server environment and it uses asynchronous programming.

Q18: Why we use Nodejs?

Ans:- Node.js is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It’s used for traditional web sites and back-end API services and real-time applications.

Q19: Who is creator of Node.js?

Ans:- Ryan Dahl

Q20: Advantage of Node.js

Ans:- Node. js offers many benefits for web app development like easy scalability, easy to learn, high performance, highly extensible, support of the large and active community.

Q21: Disadvantage of Node.js

Ans:- Not efficient in handling CPU-intensive apps. Being an event-based and a single threaded environment.

Q22: What is NPM?

NPM is a package manager for Node.js packages.

Q23: Which framework is most commonly used in Node.js?

express, Meteor,Koa,LoopBack.

Q24: What are the two types of API functions in Node.js?

The two types of API functions in Node.js are
a) Asynchronous, non-blocking functions
b) Synchronous, blocking functions

Q25: What is the use of Underscore variable in REPL?

_ symbol returns the result of the last logged expression in REPL node console.

Q26: What are local installations and global installation of dependencies?

local installations:-
when you use below command
[php]
npm install package-name
[/php]
then save it, in your project node_modules directory.

global installation:-
when you use g in the below command.
[php]
npm install -g package-name
[/php]
then save it,in your global node_modules directory and global node_modules directory situated where you installed Nodejs.

When we use
[php]
npm install package-name –save
[/php]
then package name installs in the dependencies object which is in the package.json file.

Q26: How to check the already installed dependencies using npm?

npm list –depth=0

Q27: How to uninstall the dependency using npm?

npm uninstall package-name –save

Q28: How to update the dependency using npm?

npm update package-name

Q29: What is callback Hell?

the concept of callbacks is great but if you need to make callback after callback then really confusing and difficult-to-read code.

Q30: What is Buffer Object in Nodejs?

The Buffer object is a global object in Node.js, and it is not necessary to import it using the require keyword.
[php]
var buf = Buffer.from(‘abc’);
console.log(buf);
[/php]

The Buffer class was introduced as part of the Node.js API to make it possible to manipulate or interact with streams of binary data.

Q31: In Node.js, which module is used for web based operations?

http module

Q32: What is Method Chaining in javascript?

Method chaining is a technique to simplify code in scenarios that involve performing multiple operations on the same object.
[php]
$(‘#my-data’)
.css(‘background’, ‘green’)
.height(100)
.fadeIn(400);
[/php]

Q33: What is Promise chaining?

we have a sequence of asynchronous tasks to be performed one after another.

[php]
new Promise(function(resolve, reject) {

setTimeout(() => resolve(1), 1000); // (*)

}).then(function(result) { // (**)

alert(result); // 1
return result * 2;

}).then(function(result) { // (***)

alert(result); // 2
return result * 2;

}).then(function(result) {

alert(result); // 4
return result * 2;

});
[/php]

Q34: Which module is used for file systems?

fs module is used.

Q35: What is the uses of __filename and __dirname variables in Node.js?

__filename tells you the absolute path of the filename where code being executed.
[php]
console.log( __filename ); //output:- /project/data/server.js
[/php]
__dirname tells you the absolute path of the directory containing the currently executing file.
[php]
console.log(__dirname) //Output:- "/project/data/"
[/php]

Q36: What is global variable and how to create this in Nodejs?

global variable means you can access this variable any where in the project.
you can create global variable through global object.
[php]
global.variable_name=’mydata’;
[/php]

Now, you can get this variable
[php]
console.log(variable_name);
[/php]

Q37: How to get post/get/parameter Data in Node.js?

req.body is used to post data
req.query is used to get data
req.params is used to the parameter value through req.params like get the ids
http://abc.com/id/23

Q38: What are the fundamental differences between Node.js and Ajax?

Nodejs is a server-side javascript while Ajax is client-side javascript.

Q39: Which method is used to import external libraries in Node.js?

require()

Q40: Difference between app.listen() and server.listen()?

app.listen() returns the HTTP server instance.
if you want to reuse the HTTP server then it is not possible through app.listen() then we need server.listen().

Example:- to run socket.io within the same HTTP server instance then need server.listen()
[php]
var express = require(‘express’);
var app = express();
var server = require(‘http’).createServer(app);
var io = require(‘socket.io’).listen(server);
server.listen(1234);
[/php]

Q41: What is Promise.all()?

Promises.all() is used to collect all promises, and rolls them up into a single promise. Once all of the inner promises resolve successfully then show successfully if any one promise rejects then Promise.all() show rejects. Promise.all() is basically used to fast execution.

What is CallBack

A function pass as a argument into another function is called Callback function. In Nodejs Asynchronous operation is handled by callback function.
The callback is designed for Asynchronous operations if you have a simple function that is synchronous. It means not necessary to use a callback on this simple function.


function userDetails(callback) {
  var name = 'John';
  callback(name);
}

function greeting(name) {
  console.log('Hello ' + name);
}

userDetails(greeting);
Output:- Hello John

Note:- In above example greeting function pass as a argument into userDetails function.

If you want to read a file in the synchronous manner then there is no need callback function.
To read a file in the synchronously manner.


var fs = require("fs"); 
var fileData = fs.readFileSync('inputFile.txt'); 
console.log(fileData.toString()); 

Note:- where fs is a library which is used to handle file-system related operations.

If you want to read a file in the asynchronous manner then there is need of callback function.
To read a file in the asynchronously manner.


var fs = require("fs"); 
fs.readFile('inputFile.txt', function (err, fileData) {   
    if (err) return console.error(err);   
    console.log(fileData.toString());   
});  

Note:- where fs is a library which is used to handle file-system related operations.

What is callback Hell?

if you need to make callback after callback like nested callback then it is very difficult to read and understand the code then we can say this situation is called Callback Hell.
Example:-


getData(function(a){
    getMoreData(a, function(b){
        getMoreData(b, function(c){ 
            getMoreData(c, function(d){ 
	            getMoreData(d, function(e){ 
		            ...
		        });
	        });
        });
    });
});

What is Error First Callback?

It is really only two rules for defining an error-first callback:
1. The first argument of the callback is reserved for an error object.
2. The second argument of the callback is reserved for any successful response data.


fs.readFile('/foo.txt', function(err, data) {
  // TODO: Error Handling
   if(err) {
    console.log('Unknown Error');
    return;
  }
  console.log(data);
});

What is Promise

The promise is used to handle async operation and its resulting value will be success or failure.
A Promise has basically three state
pending: initial state, neither fulfilled nor rejected.

fulfilled: meaning that the operation completed successfully.
it uses the resolve method for this

rejected: meaning that the operation failed.
it is use reject method for this.


function checkPostiveNumber (number) {
 
  return new Promise((resolve, reject) => {

  try { 
         if((number<0))
         {
            throw new Error(` ${number} is not a postive number` );
         } 
        } catch(msg) {
            reject(`Error in callback ${msg}`); 
        }

        resolve(`${number} is a positive number`)
});
}

let data=checkPostiveNumber(1);
console.log(data);
Promise {: "1 is a postive number"}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "1 is a postive number"

How to handle the Unhandled exceptions

Handling unhandled exceptions in Node.js is crucial for building robust and stable applications. Unhandled exceptions occur when an error is thrown that isn’t caught by any try...catch block or other error-handling mechanisms. If not properly managed, these exceptions can crash your Node.js process.

Methods to Handle Unhandled Exceptions

1. Global Exception Handling with process.on('uncaughtException', ...)

Node.js provides a way to catch unhandled exceptions globally using the uncaughtException event. This event is emitted when an exception bubbles all the way up without being caught.

Example:


process.on('uncaughtException', (err) => {
    console.error('There was an uncaught error:', err);
    // Perform cleanup tasks if necessary
    process.exit(1); // Exit the process after handling the exception
});

// Example of an unhandled exception
setTimeout(() => {
    throw new Error('Oops! Something went wrong.');
}, 1000);

Important:

Exiting the Process: After catching an unhandled exception, it’s usually recommended to exit the process (process.exit(1)), as the state of the application may be compromised.

2. Promise Rejection Handling with process.on('unhandledRejection', ...)

Example:

With the rise of Promises in JavaScript, unhandled promise rejections became a common source of issues. Node.js provides a way to catch these globally.


process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);
    // Perform cleanup tasks if necessary
    process.exit(1); // Exit the process after handling the rejection
});

// Example of an unhandled promise rejection
new Promise((resolve, reject) => {
    reject(new Error('Promise rejection error!'));
});

3. Graceful Shutdown

When an unhandled exception occurs, it’s often better to shut down the application gracefully after logging the error and performing necessary cleanups.


process.on('uncaughtException', (err) => {
    console.error('Unhandled Exception:', err);
    // Perform cleanup
    server.close(() => {
        process.exit(1); // Exit after closing the server
    });
});

process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection:', reason);
    // Perform cleanup
    server.close(() => {
        process.exit(1); // Exit after closing the server
    });
});

4. Use a Logger

Implement a logging mechanism to keep track of errors. Libraries like winston or bunyan can be useful for this purpose.


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

process.on('uncaughtException', (err) => {
    logger.error('Unhandled Exception:', err);
    process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
    logger.error('Unhandled Rejection:', reason);
    process.exit(1);
});

How to create Server

To create the server we need some packages

1) firstly install express package


npm i express –save

2) after that install http package


npm i http –save

Now, create the file server.js and put the below code


var http = require('http');
var express= require('express');
var app=express();
const httpServer = http.createServer(app);
httpServer.listen(4444,() => {
    console.log('HTTP Server running on port 4444');
});

Note:- 4444 is a port number where Nodejs will run and you can create any port number according to you.

//run the file
node filename


node server.js
Output:- http://localhost:4444

HTTP Server running on port 4444

Note:- where require method is use to include the module.

What is Nodejs

Node.js is a runtime environment that allows you to execute JavaScript code outside of a web browser. It is built on the V8 JavaScript engine, which is the same engine used by Google Chrome to run JavaScript in the browser.

Node js is based on javascript and it works for the server-side environment. It is a single-threaded and it handles asynchronous programming.

Node js is created by Ryan Dahl. Node. js is primarily used for non-blocking, event-driven servers. It is used for traditional web sites and back-end API services and real-time applications.

key points about Node.js

1. Server-Side JavaScript: Traditionally, JavaScript was primarily used for client-side scripting in web browsers. Node.js allows JavaScript to be used for server-side development, enabling you to build scalable, high-performance web applications with JavaScript on the server.

2. Asynchronous and Event-Driven: Node.js is designed to handle asynchronous operations efficiently. It uses an event-driven, non-blocking I/O model, making it well-suited for applications that need to handle a large number of concurrent connections, such as web servers, chat applications, and real-time applications.

3. NPM (Node Package Manager): Node.js comes with NPM, a package manager that provides access to a vast ecosystem of open-source libraries and tools. NPM makes it easy to install, share, and manage dependencies in Node.js projects.

4. Single-Threaded but Scalable: Although Node.js operates on a single thread, it can manage multiple connections simultaneously through its non-blocking architecture. This makes it capable of handling high concurrency, but it may not be the best choice for CPU-intensive tasks.

5. Use Cases: Node.js is often used for building web servers, RESTful APIs, real-time chat applications, microservices, and even desktop applications using frameworks like Electron.

6. Cross-Platform: Node.js is cross-platform, meaning it can run on various operating systems, including Windows, macOS, and Linux.

Advantages vs Disadvantage

Advantages:- Node. js offers many benefits for web app development like easy scalability, easy to learn, high performance, highly extensible, support of the large and active community.

Disadvantage:- Not efficient in handling CPU-intensive apps due to the single-threaded environment.

Nodejs Setup

Nodejs setup based on operating systems like Windows, Linux, and Mac.

Nodejs setup in Linux

there is some command to install Nodejs.


1) sudo apt-get install curl
2) curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

Now, Install Nodejs


3) sudo apt-get install nodejs

After installed Nodejs check the version


node -v 
npm -v

Now, create a test.js file and put the below code

test.js


console.log("Hello Node");

// run this file

node filename


node test.js
Output:- Hello Node

Nodejs setup in Window

Firstly open the URL https://nodejs.org/en/download/ after that click on the Windows Installer link to download this.

after download then double click on the setup and click on the Next button

Now, accept the License Agreement then click on the Next button

Now, change the path where you want to install Nodejs then click on the Next button

Now, click on the ok button

Now select the npm package manager and click on the Next button

Now, click on the Next button

Now, click on the Install button

Now, software is running mode

Now, Node.js has been successfully installed

Now, check the version of Nodejs and npm


node -v 
npm -v

Nodejs connect with Mysql

To connect with MySQL, Firstly we have to install MySQL module in the Nodejs


npm i mysql --save

now create connection.js file


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

// Now create server.js file


now include the connection.js file
const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

Now run the server.js file


node server.js

Note:- if you add correct database credentials the show “db is connected” otherwise not.

Nodejs connect with MongoDB

To connect with MongoDB, Firstly we have to install the MongoDB module in the Nodejs


npm install mongodb --save

Now, create a server.js file and put the below code


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/databaseName";
// Connect to the db
MongoClient.connect(url, function (err, db) {
   
     if(err) throw err;

     console.log("Database connected");
                
});

Now check database is connected or not


node server.js

If connected then show message “Database connected” otherwise not.

Get method API in Nodejs

firstly create the users collection and save all documents.


let users=[
{_id:1,name:"Rom",age:30},
{_id:2,name:"Tony",age:31},
{_id:3,name:"Peter",age:32},
{_id:4,name:"Andrew",age:33},
{_id:5,name:"Symonds",age:34},
{_id:6,name:"John",age:35},
{_id:7,name:"Ponting",age:36},
]

var MongoClient = require('mongodb').MongoClient;
let url="mongodb://localhost:27017/databaseName";
MongoClient.connect(url, function (err, db) {

db.collection("users").insertMany(users, function(err, res) {
    if (err) throw err;
    console.log("all documents are inserted");
    db.close();
  });

 });

Create the get method API to get all documents from the MongoDB


var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;

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

    MongoClient.connect(url, function (err, db) {

    if(!err){

    db.collection("users").find().toArray(function(err, result) {

    if (err){
      res.json({data:result,messages:"some thing went wrong",status:501})
    }

   res.json({data:result,messages:"users list show successfully",status:200})

    db.close();
  });

  }else{

   res.json({data:err,messages:"some thing went wrong",status:501})
  }

});

});

if you need the details of the specific user


var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
app.get('/user/:id', function (req, res) {

    MongoClient.connect(url, function (err, db) {

    if(!err){
    
    let req_params=req.params;
    let user_id=(typeof req_params.id !== 'undefined') ? (req_params.id):0;
 
    db.collection("users").find({_id:user_id}).toArray(function(err, result) {

    if (err){
      res.json({data:result,messages:"some thing went wrong",status:501})
    }

    res.json({data:result,messages:"user details show successfully",status:200})

    db.close();
  });

  }else{

   res.json({data:err,messages:"some thing went wrong",status:501})
  }

});

});

Note:- In the above example req.params is used to get the route parameters value.

Post method API in Nodejs

Create the POST method API to insert the document in the MongoDB

Suppose, You have users collection which has three fields
1) _id
2) name
3) email


var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
app.post('/addUser', function (req, res) {

    MongoClient.connect(url, function (err, db) {

    if(!err){

    let req_body=req.body;
    let user_name=(typeof req_body.name !== 'undefined') ? (req_body.name).trim():"";
    let user_email=(typeof req_body.email !== 'undefined') ? (req_body.email).trim():"";

    let user_details={
    "name":user_name,
    "email":user_email
    }

    db.collection("users").insertOne(user_details,function(err, result) {

    if (err){
      res.json({data:result,messages:"some thing went wrong",status:501})
    }

   res.json({data:result,messages:"user add successfully",status:200})

    db.close();
  });

  }else{

   res.json({data:err,messages:"some thing went wrong",status:501})
  }

});

});

Note:- In the above example req.body is used to get the URL body parameters value.

Put method Api in Nodejs

Create the PUT method API to update the document in the MongoDB
Suppose, You have users collection which has three fields
1) _id
2) name
3) email


let users=[
{_id:1,name:"Rom",age:30},
{_id:2,name:"Tony",age:31},
{_id:3,name:"Peter",age:32},
{_id:4,name:"Andrew",age:33},
{_id:5,name:"Symonds",age:34},
{_id:6,name:"John",age:35},
{_id:7,name:"Ponting",age:36},
]

PUT method API code


var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
app.put('/updateUser/:id', function (req, res) {

    MongoClient.connect(url, function (err, db) {

    if(!err){

    let req_params=req.params;
    let req_body=req.body;

    let user_id=(typeof req_params.id !== 'undefined') ? (req_params.id):0;
    let user_name=(typeof req_body.name !== 'undefined') ? (req_body.name).trim():"";
    let user_email=(typeof req_body.email !== 'undefined') ? (req_body.email).trim():"";
   

    let user_details={
    "name":user_name,
    "email":user_email
    }

    db.collection("users").UpdateOne({"_id":user_id},{$set:user_details},function(err, result) {

    if (err){
      res.json({data:result,messages:"some thing went wrong",status:501})
    }

   res.json({data:result,messages:"user update successfully",status:200})

    db.close();
  });

  }else{

   res.json({data:err,messages:"some thing went wrong",status:501})
  }

});

});

Note:- In the above example req.body is used to get the URL body parameters value and req.params is used to get the route parameters value.

Delete method Api in Nodejs

Create the delete method API to delete the document from the MongoDB.

Suppose, You have users collection which has three fields
1) _id
2) name
3) email


let users=[
{_id:1,name:"Rom",age:30},
{_id:2,name:"Tony",age:31},
{_id:3,name:"Peter",age:32},
{_id:4,name:"Andrew",age:33},
{_id:5,name:"Symonds",age:34},
{_id:6,name:"John",age:35},
{_id:7,name:"Ponting",age:36},
]

DELETE method API code


var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
app.delete('/deleteUser/:id', function (req, res) {

    MongoClient.connect(url, function (err, db) {

    if(!err){

    let req_params=req.params;

    let user_id=(typeof req_params.id !== 'undefined') ? (req_params.id):0;
  
    db.collection("users").deleteOne({"_id":user_id},function(err, result) {

    if (err){
      res.json({data:result,messages:"some thing went wrong",status:501})
    }

   res.json({data:result,messages:"user delete successfully",status:200})

    db.close();
  });

  }else{

   res.json({data:err,messages:"some thing went wrong",status:501})
  }

});

});

Note:- In the above example req.params is used to get route parameters value.
I think a hard delete of a record is not good so we should use soft delete.

Patch method Api in Nodejs

PATCH method is used when you want to update the resource like update the name, status etc. PATCH method is faster than PUT method. PUT method basically used when you want to modify the whole resource value.

Suppose, You have users collection which has three fields
1) _id
2) name
3) email


let users=[
{_id:1,name:"Rom",age:30},
{_id:2,name:"Tony",age:31},
{_id:3,name:"Peter",age:32},
{_id:4,name:"Andrew",age:33},
{_id:5,name:"Symonds",age:34},
{_id:6,name:"John",age:35},
{_id:7,name:"Ponting",age:36},
]

Create the patch method API to update the document in the MongoDB


var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
app.patch('/updateUser/:id', function (req, res) {

    MongoClient.connect(url, function (err, db) {

    if(!err){

    let req_params=req.params;
    let req_body=req.body;

    let user_id=(typeof req_params.id !== 'undefined') ? (req_params.id):0;
    let user_name=(typeof req_body.name !== 'undefined') ? (req_body.name).trim():"";

    let user_details={
    "name":user_name
    }

    db.collection("users").UpdateOne({"_id":user_id},{$set:user_details},function(err, result) {

    if (err){
      res.json({data:result,messages:"some thing went wrong",status:501})
    }

   res.json({data:result,messages:"user update successfully",status:200})

    db.close();
  });

  }else{

   res.json({data:err,messages:"some thing went wrong",status:501})
  }

});

});

Note:- In the above example req.body is used to get the URL body parameters value and req.params is used to get the route parameters value.

What is Restful Api

REST stands for REpresentational State Transfer and is used to access and manipulate data using several stateless operations. These operations are integral to the HTTP protocol and represent an essential CRUD functionality (Create, Read, Update, Delete).

Http method are

GET:- It is used to get the resource.

POST:- It is used to add the resource.

PUT:- It is used to update the resource.

DELETE:- It is used to delete the resource.

PATCH:- It is used to update the small part of the resource.

Note:-In the Restful API, we use JSON date to perform all actions.

users collection JSON data


{
[
{ _id:1, name:"Rom", age:30 },

{ _id:2, name:"Tony", age:31 },

{ _id:3, name:"Peter", age:32 },

{ _id:4, name:"Andrew", age:33 },

{ _id:5, name:"Symonds", age:34 },

{ _id:6, name:"John", age:35 },

{ _id:7, name:"Ponting", age:36 }
]
}

What is REPL

REPL stands for Read Eval Print Loop. It basically represents a computer environment like Linux/Unix terminal, window console, etc.
It comes with a Nodejs package so you do not need to install it separately.

firstly open the terminal
run the node command


$ node

now You will see the REPL Command prompt > where you can type any Node.js command


$ node 
>

// Add the two string


> "John"+" "+"Roser"
John Roser

// Add the numeric value


>1+2+4
7

Note:- to terminate the command we use ctrl+c

environment variable setup in Nodejs

to setup the environment variable through dotenv module

firstly install dotenv module


npm install dotenv

Now create the .env file in the root folder of your project

in the .env file put the below code

Write the credentials


DB_HOST=localhost
DB_USER=root
DB_PASS=12sdf
DB_NAME=myportal

Now include the env module in your main file like server.js


const env_result =require('dotenv').config();

// Now, get the envorment credentials through


process.env.enviormentVariableName like "process.env.DB_HOST"

include the environment credentials into server.js


var MongoClient = require('mongodb').MongoClient;
 
var url = `mongodb://${encodeURIComponent(process.env.DB_USER)}:${encodeURIComponent(process.env.DB_PASS)}@localhost:27017/process.env.DB_NAME`;

// Connect to the db
MongoClient.connect(url, function (err, db) {
    
     if(err) throw err;
 
     console.log("Database connected");
                 
});

Event Loop

The Event Loop is a fundamental concept in Node.js that allows it to handle asynchronous operations efficiently. Understanding how the Event Loop works is crucial for grasping how Node.js manages non-blocking I/O operations and concurrency.

Overview of the Event Loop

Node.js is single-threaded, meaning it operates on a single thread of execution. However, it can handle multiple operations concurrently thanks to the Event Loop, which enables asynchronous, non-blocking I/O operations. This design makes Node.js particularly well-suited for I/O-bound tasks like web servers, where handling many simultaneous connections efficiently is critical.

How the Event Loop Works?

1. Call Stack:

This is where function calls are executed one at a time. JavaScript is single-threaded, so only one operation can occur at a time in the call stack.

2. Node APIs/Thread Pool:

When an asynchronous operation (like I/O, timers, or network requests) is invoked, it’s offloaded to the Node.js APIs, which might leverage a thread pool to handle the operation in the background.

3. Callback Queue (Task Queue):

Once an asynchronous operation is completed, its callback is placed in the Callback Queue. These callbacks are functions that should be executed once the result of an asynchronous operation is ready.

4. Event Loop:

The Event Loop continuously monitors the Call Stack and the Callback Queue.

If the Call Stack is empty, the Event Loop picks the first callback from the Callback Queue and pushes it to the Call Stack for execution.

This cycle repeats, enabling Node.js to handle asynchronous operations without blocking the main thread.

Phases of the Event Loop

The Event Loop operates in several phases, where each phase handles different types of callbacks:

1. Timers Phase:

Handles callbacks from setTimeout() and setInterval() once the specified time has elapsed.

2. I/O Callbacks Phase:

Processes callbacks from some system operations like errors or connection completion callbacks (excluding file, network, and setTimeout).

3. Idle, Prepare Phase:

Internal use only. Prepare handles callbacks executed right before the poll phase.

4. Poll Phase:

Retrieves new I/O events and executes I/O-related callbacks. It also manages the blocking of the event loop when no tasks are queued.

5. Check Phase:

Handles callbacks from setImmediate(). These callbacks are executed after the poll phase.

6. Close Callbacks Phase:

Executes callbacks for close events, such as when a socket or handle is closed.

Example to Illustrate the Event Loop


console.log('Start');

setTimeout(() => {
    console.log('Timeout');
}, 0);

setImmediate(() => {
    console.log('Immediate');
});

console.log('End');

Output:

Start
End
Immediate
Timeout

Explanation:

The console.log('Start') and console.log('End') execute immediately because they are synchronous.

setTimeout(() => {...}, 0) schedules the callback in the Timer phase but waits until the next tick of the event loop.

setImmediate(() => {...}) schedules the callback for the Check phase.

Since the Event Loop checks the setImmediate queue before it checks the Timer queue, “Immediate” is logged before “Timeout”.

An event loop has One Process, One Thread and One Event Loop.

Now, let’s take a look at how our code runs inside of the Node.js instance.


console.log('Task 1');
console.log('Task 2');

// some time consuming for loop
for(let i = 0; i < 999999; i++) {
}

console.log('Task 3');

What happens when we run this code? It will first print out Task 1 than Task 2 and then it will run the time consuming by the for a loop after that it will print out Task 3.

Node puts all our tasks into an Events queue and sends them one by one to the event loop. The event loop is single-threaded and it can only run one thing at a time. So it goes through Task 1 and Task 2 then the very big for loop and then it goes to Task 3. This is why we see a pause in the terminal after Task 2 because it is running the for a loop.
Now let’s do something different. Let’s replace that for loop with an I/O event.


console.log('Task 1');
console.log('Task 2');
fs.readFile('./file.txt', (err, data) => {
    if (err) throw err;
    console.log('done reading file');
    process.exit();
});
console.log('Task 3');

Now the result is
Task 1
Task 2
Task 3
done reading file

I/O tasks, network requests, database processes are classified as blocking tasks in Node.js. So whenever the event loop encounters these tasks it sends them off to a different thread and moves on to the next task in events queue. A thread gets initiated from the thread pool to handle each blocking tasks and when it is done, it puts the result in a call-back queue. When the event loop is done executing everything in the events queue it will start executing the tasks in the call-back queue.

Worker Thread

Worker Threads in Node.js are a feature that allows you to execute JavaScript code in parallel across multiple threads. This feature is particularly useful for performing CPU-intensive tasks that would otherwise block the main thread and degrade performance in a single-threaded, event-driven environment like Node.js.

Why Use Worker Threads?

Node.js is single-threaded, meaning that all code execution happens on a single thread. This is fine for I/O-bound operations because the Event Loop efficiently handles these operations asynchronously. However, for CPU-intensive tasks (like complex calculations, data processing, or image manipulation), the single-threaded nature of Node.js can become a bottleneck, as these tasks can block the Event Loop, causing delays in handling other tasks.

Worker Threads allow you to offload these heavy computations to separate threads, enabling better concurrency and responsiveness in your Node.js applications.

How Worker Threads Work

Worker Threads are part of the worker_threads module, introduced in Node.js v10.5.0 (and stabilized in Node.js v12). Each worker thread runs in its own isolated JavaScript environment, meaning it has its own event loop, memory, and V8 instance. This isolation ensures that a blocking operation in one worker thread does not block the main thread or other worker threads.

Basic Example:

Step 1: Create a Worker Thread

Create a file named worker.js that contains the code to be executed by the worker thread:


// worker.js
const { parentPort } = require('worker_threads');

// Perform a CPU-intensive task
let count = 0;
for (let i = 0; i < 1e9; i++) {
    count += i;
}

// Send the result back to the main thread
parentPort.postMessage(count);

Step 2: Use the Worker in the Main Thread

Create a file named main.js to spawn the worker and handle the results:


const { Worker } = require('worker_threads');

// Create a new worker thread
const worker = new Worker('./worker.js');

// Listen for messages from the worker thread
worker.on('message', (result) => {
    console.log(`Result from worker: ${result}`);
});

// Listen for errors from the worker thread
worker.on('error', (err) => {
    console.error(`Worker error: ${err}`);
});

// Listen for the worker thread to exit
worker.on('exit', (code) => {
    if (code !== 0)
        console.error(`Worker stopped with exit code ${code}`);
});

console.log('Main thread is still responsive...');

Step 3: Run the Main Thread

Execute the main.js file:


node main.js

Output:

Main thread is still responsive...
Result from worker: 499999999500000000

Explanation:

The main thread spawns a worker thread to perform a CPU-intensive calculation (summing numbers).

While the worker is busy, the main thread remains responsive and can handle other tasks.

Once the worker completes its task, it sends the result back to the main thread via a message.

When to Use Worker Threads?

CPU-Intensive Tasks: Use worker threads for tasks that involve heavy computation, such as image processing, video encoding, data compression, and mathematical calculations.

Parallel Processing: If you need to perform parallel processing, worker threads are an effective way to leverage multiple CPU cores.

Isolated Execution: When you want to run code in an isolated environment, worker threads ensure that memory and event loops are separated.

When Not to Use Worker Threads

I/O-Bound Tasks: For I/O-bound tasks, the asynchronous, non-blocking nature of Node.js is usually sufficient. Worker threads add complexity and overhead, so they are not needed in these cases.

Simple Applications: If your application does not involve CPU-intensive operations, worker threads may not provide a significant benefit.

Worker Threads Diagram

1 Event Loop per thread
1 JS Engine Instance per thread
1 Node.js Instance per thread

Since worker_threads make new threads inside the same process it requires fewer resources. Also, we are able to pass data between these threads because they have a shared memory space.

Event Emitter

In Node.js, the EventEmitter is a core module that allows you to create and handle custom events. It’s a fundamental concept in Node.js and is used extensively throughout the platform, including in many of the built-in modules like HTTP, Streams, and File System modules.

Nodejs follow Event-Driven based architecture so every action is an event in Nodejs like open the file to read is an event.

What is EventEmitter?

EventEmitter is a class that provides a way to emit (or trigger) named events and subscribe to them. This allows different parts of your application to communicate with each other in a decoupled way, making it easier to manage complex systems where multiple components need to interact.

Key Features of EventEmitter

1. Emit Events: The EventEmitter allows an object to emit an event, signaling that something has occurred. Other parts of the program can listen for this event and execute code in response.

2. Add Listeners: You can register listeners (callback functions) for specific events. These listeners will be triggered whenever the corresponding event is emitted.

3. Handle Multiple Events: The EventEmitter can manage multiple events, each with multiple listeners.

4. Asynchronous and Synchronous Events: Events can be handled synchronously (where the event listeners are called immediately) or asynchronously (allowing other code to run before the event listeners are called).

Basic Usage:

1. Importing the events module:


const EventEmitter = require('events');

2. Creating an EventEmitter instance:


const eventEmitter = new EventEmitter();

3. Adding a listener for an event:


var customEventHandler = ()=> { 
console.log('an event occurred!'); 
} 

eventEmitter.on('customEventName', customEventHandler);

4. Emitting an event:


eventEmitter.emit('customEventName');

Example


const EventEmitter = require('events');

// Create an instance of EventEmitter
const myEmitter = new EventEmitter();

// Define a listener for the 'greet' event
myEmitter.on('greet', (name) => {
    console.log(`Hello, ${name}!`);
});

// Emit the 'greet' event with a name as an argument
myEmitter.emit('greet', 'John');

Output:

Hello, John!

Key Methods

Registers a listener for a specific event. This listener will be called every time the event is emitted.

on(eventName, listener):: Emits an event, invoking all the listeners registered for that event, and passing them any provided arguments.

once(eventName, listener): Registers a listener that will be invoked only the first time the event is emitted. After that, it is automatically removed.

removeListener(eventName, listener): Removes a specific listener from an event, so it will no longer be called when the event is emitted.

removeAllListeners([eventName]): Removes all listeners for a given event, or all events if no event name is provided.

Example:

We want to alert everyone when a new user joins the chat room. We’ll need an event listener for a userJoined event. First, we’ll write a function that will act as our event listener, then we can use EventEmitters on the method to set the listener.


const events = require('events');
const chatRoomEvents = new events.EventEmitter;

function userJoined(username){
  // Assuming we already have a function to alert all users.
  alertAllUsers('User ' + username + ' has joined the chat.');
}

// Run the userJoined function when a 'userJoined' event is triggered.
chatRoomEvents.on('userJoined', userJoined);

The next step would be to make sure that our chat room triggers a userJoined event whenever someone logs in so that our event handler is called. EventEmitter has an emit method that we use to trigger the event. We would want to trigger this event from within a login function inside of our chatroom module.


function login(username){
  chatRoomEvents.emit('userJoined', username);
}

there are lots of default events in Nodejs but I am showing some events.


newListener('eventName',listener)

It is called when we want to add listner in the event.


removeListener('eventName',listener);

It is called when we want to remove listner from the event.


once('eventName', listener)

Adds a one-time listener function for the event named eventName

Streams

Streams in Node.js are a powerful way to handle reading and writing data. They are especially useful for working with large datasets or when you want to process data before it’s fully loaded, such as reading from a file or making HTTP requests. Streams allow you to work with data piece by piece (chunks), which is more efficient in terms of memory usage and processing time compared to reading the entire data at once.

Stream workflow “read from the input and write to output sequentially.

Types of Streams in Node.js

There are 4 types of Streams

1. Readable Streams: Used for reading data. Examples include fs.createReadStream(), HTTP requests, and responses.

2. Writable Streams: Used for writing data. Examples include fs.createWriteStream(), HTTP requests, and responses.

3. Duplex Streams: These are both readable and writable. An example is a network socket.

4. Transform Streams: These are duplex streams that can modify or transform the data as it is read or written. Examples include zlib.createGzip() for compression.

Why Use Streams?

Memory Efficiency: Streams handle data in chunks, reducing the memory footprint by not loading the entire data into memory at once.

Time Efficiency: Streams allow you to start processing data as soon as you receive it, which can be faster than waiting for all data to arrive.

Handling Large Files: When working with large files, streams allow you to read or write the data in chunks without consuming too much memory.

some events of the stream

1) data: this event is fired to read the data.

2) end: this event is fired when no data is available to read.

3) error: This event is fired when there is any error to read or write data.

4) finish: This event is fired when all the data has been flushed to the underlying system.

Basic Example of a Readable Stream

Here’s an example of reading a file using a readable stream:


const fs = require('fs');

// Create a readable stream from a file
const readableStream = fs.createReadStream('example.txt', {
    encoding: 'utf8',
    highWaterMark: 16 * 1024 // 16KB chunk size
});

// Listen for data events, which provide chunks of data as they are read
readableStream.on('data', (chunk) => {
    console.log('New chunk received:');
    console.log(chunk);
});

// Handle the end of the stream
readableStream.on('end', () => {
    console.log('No more data to read.');
});

// Handle errors
readableStream.on('error', (err) => {
    console.error('Error:', err);
});

Basic Example of a Writable Stream

Now, let’s see how to write data using a writable stream:


const fs = require('fs');

// Create a writable stream to a file
const writableStream = fs.createWriteStream('output.txt');

// Write data to the stream
writableStream.write('Hello, ');
writableStream.write('World!\n');

// End the stream
writableStream.end();

// Handle stream finish event
writableStream.on('finish', () => {
    console.log('All data written to file.');
});

// Handle errors
writableStream.on('error', (err) => {
    console.error('Error:', err);
});

Piping Streams

One of the most common use cases for streams is piping, where you connect a readable stream to a writable stream. This is particularly useful for tasks like reading from a file and immediately writing to another file or responding to an HTTP request.

Here’s an example of piping a readable stream to a writable stream:


const fs = require('fs');

// Create a readable stream and a writable stream
const readableStream = fs.createReadStream('example.txt');
const writableStream = fs.createWriteStream('output.txt');

// Pipe the readable stream into the writable stream
readableStream.pipe(writableStream);

// Handle the finish event
writableStream.on('finish', () => {
    console.log('File successfully copied.');
});

Transform Streams

Transform streams are special types of streams that modify the data as it passes through. For example, you can compress a file using a transform stream.

Here’s an example of compressing a file using the zlib module:


const fs = require('fs');
const zlib = require('zlib');

// Create a readable stream, a writable stream, and a transform stream
const readableStream = fs.createReadStream('example.txt');
const gzipStream = zlib.createGzip();
const writableStream = fs.createWriteStream('example.txt.gz');

// Pipe the readable stream through the transform stream and then to the writable stream
readableStream.pipe(gzipStream).pipe(writableStream);

// Handle the finish event
writableStream.on('finish', () => {
    console.log('File successfully compressed.');
});

Error Handling in Streams

Error handling is crucial when working with streams. You can listen for error events on any stream to catch and handle errors:


readableStream.on('error', (err) => {
    console.error('Read error:', err);
});

writableStream.on('error', (err) => {
    console.error('Write error:', err);
});