HI WELCOME TO SIRIS
Showing posts with label node.js. Show all posts
Showing posts with label node.js. Show all posts

Node.Js Events EventEmitter Tutorial Example From Scratch

Leave a Comment
Node.js Events EventEmitter Tutorial Example From Scratch is today’s leading topic. EventEmitter is the implementation of Node.js’s pub-sub design patterns. Node.js core API has built on an asynchronous event-driven architecture. In an asynchronous event architecture, certain kinds of objects (called “emitters”) periodically emit named events that cause Function objects (“listeners”) to be called.

Each object that emits events are instances of an EventEmitter class.
We are going to see one example with ES5 Syntax.
Node.js Events EventEmitter

Example #1

// ES5 Event Emitter Example

var events = require('events').EventEmitter;
var emitter = new events.EventEmitter();

emitter.on('newEvent', function(user){
    console.log(user);
});

emitter.emit('newEvent', "Sireesh");
In above example, first, we are going to import events object, and then we get emitter object.
The event emitter class has two methods.
  1. On
  2. emit
So, if we make an object of EventEmitter class, then we have access to this methods.
emitter.on('newEvent', function(user){
    console.log(user);
});
Here, I have defined an event and till now, not called just determine.
On() method takes an event name and a call back function, which describes the logic and payload of the function. As we know, Node.js has the event-driven architecture, so it first occurs the events and then related to that event, one callback function is returned.
emitter.emit('newEvent', "Sireesh");
Here, I have emitted the event, so related to that event, the callback function is invoked, and that function will execute. The first parameter is event name and second is payload.
The output will be following.
Sireesh

Example #2

var EventEmitter = require('events').EventEmitter;
var util = require('util');

var User = function(username){
    this.username = username;
}
util.inherits(User, EventEmitter);
var user = new User('Sireesh Kantamaneni');
user.on('nuevent', function(props){
    console.log(props);
});
user.emit('nuevent', 'dancing');
In this example, first I have created an EventEmitter object and then also create User function constructor.
Then, import the Node.js’s core module util and inherits the base functionality from EventEmitter module to the newly created User module.
So, now User has all the methods and properties of the EventEmitter module, and we can use two methods on it.
Now, user object’s behavior is same as EventEmitter, and we can define events on it and emit the events.
The output will be “dancing.”

Example #3

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
  console.log('an event occurred!');
});
myEmitter.emit('event');
Above is an ES6 example of Node.js events and event emitter.
First, we have included the EventEmitter class, and then we define our class and extends the base EventEmitter class.

Now, make an object of the newly created class, so we have access all the methods of the EventEmitterclass. Rest is all the same.

Google Recaptcha In Node.Js Tutorial From Scratch

Leave a Comment
Google Recaptcha In Node.js Tutorial From Scratch topic we will cover today. Google Recaptcha is a kind of security through you can prevent the computer bots, spammers to enter your website. We are using Node.js and express framework to build a Google Recaptcha Security. So let us get started.

Step 1: Create a project and configure it.

Create your project folder and inside type following command in your terminal.
npm init
We are initializing the package.json file.
{
  "name": "googlerecaptcha",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon server"
  },
  "author": "Sireesh Kantamaneni",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "ejs": "^2.5.7",
    "express": "^4.15.4"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }
}
We have written three packages as dependencies, so go to your terminal and type the command.
npm install
Now, create one file in a root called server.js and also create one folder name public in the root.
// Server.js

var express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser');

var app = express();
   app.set('view engine', 'ejs');
   app.use(express.static('public'));
   app.use(bodyParser.urlencoded({extended: true}));
   app.use(bodyParser.json());
   var port = 3000;

app.listen(port, function(){
    console.log('Server is running at port: ',port);
});
Here, I have required all the modules and used express in our application. Static files are served from public folder and use body-parser middleware to extract the data from Post request. We have used ejs as a templating engine for our application.

Step 2: Set up the views for our project. 

Create one folder in root called views. In that folder, create one ejs file called index.ejs. We are using Bootstrap CSS Framework for this application, so include that CSS file in public folder.
<!-- index.ejs -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Google Recaptcha Tutorial</title>
    <link rel="stylesheet" href="bootstrap.min.css">
  </head>
  <body>
    <div class="container"><br />
      <h1>Google Recaptcha Tutorial</h1><br />
      <form action="/send-email" method="post">
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="name">Name:</label>
            <input type="text" class="form-control" name="name">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Send</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>
To access this page, we need to set up one route in a server.js file.
// server.js

app.get('/', function (req, res) {
    res.render('index');
});
Go to your terminal, type following command.
npm start
Switch to your browser and type this URL: http://localhost:3000
You will see a form with one field.

Step 3: Configure Google reCaptcha with your Google account. 


Now, you need to register your site with this URL: https://www.google.com/recaptcha to get the API key and API secret.

How To Send Email In Node.Js Tutorial

Leave a Comment
How To Send Email In Node.js Tutorial is today’s main topic. We will use an Express Framework on the top of the Node.js application. Sending the emails in our web application is always there no matter what type of web application you are building. Today, I will show you how to do this with an example. Send email in Node.js tutorial with an example.
Send Email In Node.js

Step 1: Create a project and configure it.

Create a project directory and in that type the following command in it.
npm init
We are going to use nodemailer package for sending the email. Also, we are using an express web framework, so let us download both of them.
npm install --save nodemailer express
To get rid of every time restart the server, we are using one package called nodemon server.
npm install nodemon --save-dev
In the root directory, create one js file called server.js
// server.js

var express = require('express'),
    path = require('path'),
    nodeMailer = require('nodemailer');

    var app = express();
    var port = 3000;
    app.listen(port, function(req, res){
      console.log('Server is running at port: ',port);
    });
This is just a boilerplate to start our project. One thing we need to do is that we need to modify start script in a package.json file.
// package.json

"scripts": {
    "start": "nodemon server"
  },
So, when we have to start the node server, we just need to write the following command. 
npm start
If we change the file, then it will restart the server automatically.

Step 2: Use EJS as a templating engine.

Now, we need to install templating engine called ejs(embedded javascript) by typing following command.
npm install --save ejs
Create one directory in the root folder called public.
// server.js

app.set('view engine', 'ejs');
app.use(express.static('public'));
We are setting ejs templating engine for our application. Also, we are serving static files from the public directory.
In the root folder, we also need to create one more folder called views. In that create one file called index.ejs.
// index.ejs

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Nodemailer Email Example</title>
    
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        Sending Email in Node.js
      </div>
    </div>
  </body>
</html>
We have used bootstrap CSS class here, so the first thing we need to do is include library inside the public folder.
<link rel="stylesheet" href="bootstrap.min.css">
Also, create one route for home page by typing following code.
// server.js

app.get('/', function (req, res) {
   res.render('index');
});
Now, if you have not started the server yet, please initiate the server by the following command.
npm start
It will start at the port 3000. Switch to the URL: http://locahost:3000

send email in expressjs

Step 3: Create a basic bootstrap form.

Create one bootstrap form to send the email. We are going to put that form in the index.ejs file.
<!-- index.ejs -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Nodemailer Email Example</title>
    <link rel="stylesheet" href="bootstrap.min.css">
  </head>
  <body>
    <div class="container"><br />
      <h1>Send The Email</h1><br />
      <form action="/send-email" method="post">
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="to">To:</label>
            <input type="email" class="form-control" name="to">
          </div>
        </div>

        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="subject">Subject:</label>
            <input type="text" class="form-control" name="subject">
          </div>
        </div>

        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="body">Body:</label>
              <textarea cols="5" rows="5"class="form-control" name="body"></textarea>
            </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Send</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>
send email using nodemailer
Our primary form will look like this.
Now, set the post action of the form.
<!-- index.rjs -->

<form action="/send-email" method="post">
However, to get all fields data at the server side, we need to install one package called body-parser package.

Step 4: Write the code that sends the email.

npm install body-parser --save
Use this package in our express framework by the following code.
// server.js

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
Next step is to create a route for the post request sent by form and handle its data. So, our final server.js file will look like this.
// server.js
var express = require('express'),
    path = require('path'),
    nodeMailer = require('nodemailer'),
    bodyParser = require('body-parser');

    var app = express();
    app.set('view engine', 'ejs');
    app.use(express.static('public'));
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    var port = 3000;
    app.get('/', function (req, res) {
      res.render('index');
    });
    app.post('/send-email', function (req, res) {
      let transporter = nodeMailer.createTransport({
          host: 'smtp.gmail.com',
          port: 465,
          secure: true,
          auth: {
              user: 'xxx@xx.com',
              pass: 'xxxx'
          }
      });
      let mailOptions = {
          from: '"Sireesh Kantamaneni" <xx@gmail.com>', // sender address
          to: req.body.to, // list of receivers
          subject: req.body.subject, // Subject line
          text: req.body.body, // plain text body
          html: '<b>NodeJS Email Tutorial</b>' // html body
      };

      transporter.sendMail(mailOptions, (error, info) => {
          if (error) {
              return console.log(error);
          }
          console.log('Message %s sent: %s', info.messageId, info.response);
              res.render('index');
          });
      });
          app.listen(port, function(){
            console.log('Server is running at port: ',port);
          });
Here, I have shown you to send the email via Gmail. You can use any other host. You just need to grab their API keys.
If you are using Gmail then please update your credentials in the options object.
If email is successfully sent then, our form page index.ejs will return otherwise check the console in the terminal. You will get an error over there. This is the example of Send email using nodemailer.
Github Steps To Follow: 
  1. Clone the repository.
  2. In the project type: npm install
  3. Go to the server.js and configure your email client.
  4. Start the server by the typing: npm start

If you have any doubt then ask in a comment below.