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

If any uncaught exception occurs in your code flow, that exception will be caught in code shown below:
[php]
process.on(‘uncaughtException’, function(err) {
// handle the error safely
console.log(err)
})
[/php]

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 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.

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

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 and One Event Loop.

Now, let’s take a look at how our code runs inside of 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

Node.js introduced worker_thread and fully supported in the Node LST version 12. This module has
1 Process
Multiple Thread
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

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.


var events = require('events');

after that create the object through new keyword.


var eventEmitter = new events.EventEmitter();

to assign the custom event we use “on” keyword

//Create an custom event handler:


var customEventHandler =  ()=> {

   console.log('an event occurred!');
}

eventEmitter.on('customEventName', customEventHandler);

fire the event through emit() method.


eventEmitter.emit('customEventName');

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

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”.

There are 4 types of Stream

1) Readable:- this is basically use to read the data.

2) Writable:- this stream is used to write the data.

3) Duplex:- this stream is used to read and write in a sequence manner.

4) Transform:- this stream is used to read the data after that manipulating it and then generate new data.

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.

Example:- if the file size is too large and we need to read data from the file then the fs.createReadStream method is useful because it will read the data from the file into chunk format.


var fs = require('fs');
var readableStream = fs.createReadStream('myfile.txt');
var data = '';

readableStream.on('data', function(chunkData) {
    data +=chunkData;
});

readableStream.on('end', function() {
    console.log(data);
});

Pipe:- through pipe() method we can read the data from one file and write the data into another file in a sequential manner.


var fs = require('fs');
var readableStream = fs.createReadStream('readFile.txt');
var writableStream = fs.createWriteStream('writeFile.txt');
readableStream.pipe(writableStream);