Loading...

Follow Codeforgeek | Node.js tutorials on Feedspot

Continue with Google
Continue with Facebook
or

Valid

To install Node.js and NPM on Ubuntu, follow the steps mentioned below:

Step 1 – Install Node

Open your terminal and run the following commands.

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

Then, install Node.

sudo apt-get install -y nodejs
Step 2 – Verify the Installation

Run the following command to verify the Node installation.

node -v

This should result in the Node version installed in your system.

Verify the NPM installation.

npm -v

Step 3 – Install build tools

Install the optional build tools for native addons.

sudo apt-get install -y build-essential

That’s it. You have installed the Node.js in your Ubuntu system.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In this tutorial, we will learn how to interact with a MongoDB database using Node.js.

MongoDB is a NoSQL database. MongoDB stores information in JSON format and can support more than just basic data types.

MongoDB is schemaless, that means we don’t need to pre-define the structure of the data. In this tutorial, we will learn how to interact with MongoDB using Node.js.

MongoDB Installation

We need to install MongoDB in our system. I highly recommend you to check out the official installation page of MongoDB.

Once we have MongoDB installed, we can validate the installation by using the Mongo shell. Open the terminal and type mongo it should connect to the MongoDB daemon.

Node and NPM Installation

Check out our guide on Node installation on Ubuntu. If you are new to Node, I highly suggest you take this free course from us.

MongoDB basics

If you are new to MongoDB and it commands. Read this quick tutorial to get a heads up.

Creating our Node project

Open your terminal and create a new folder.

mkdir mongotest

Run this command to create a fresh Node project. It’s a good practice.

npm init --y

Let’s install the official MongoDB node module.

npm install --save mongodb
Connecting to MongoDB

Here is the code to connect to the MongoDB using Node.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
        if(err) {
           console.log(err);
           process.exit(0);
        }
        console.log('database connected!');
        db.close();
});

Change the value of an URL if you are using MongoDB remote instance. All we did here is just fire up the connection and see if works. Here is a screenshot.

Next, we need to select the database and create our collection in it.

Here is the code to do the same.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
        if(err) {
           console.log(err);
           process.exit(0);
        }
        console.log('database connected!');
        var dbo = db.db('codeforgeek');
        dbo.createCollection('users', (err, result) => {
            if(err) {
               console.log(err);
               process.exit(0);
            }
            console.log('collection created!');
            db.close();
        });
});

After a successful MongoDB connection, we select the MongoDB database.

        var dbo = db.db('codeforgeek');

Then, we try to create a collection naming users in the codeforgeek database.

Inserting data in the collection

Let’s add a few entries in our collection. Consider the code below.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
    if(err) {
       console.log(err);
       process.exit(0);
    }
    let data = [{
       "id": 100,
        "name": "Shahid"
    },{
        "id": 101,
        "name": "Rahil"
    },{
        "id": 102,
        "name": "John"
    }];
    var dbo = db.db('codeforgeek');
    console.log('database connected!');
    var collection = dbo.collection('users');
    collection.insertMany(data, (err, result) => {
        if(err) {
            console.log(err);
            process.exit(0);
        }
        console.log(result);
        db.close();
    });
});

In the code shown above, we are using insertMany() function to add multiple entries at one go. However, you can also use insertOne() function to add single entries if you like.

This code should output something similar to this screenshot.

Find the data in collection

We can use find() function to search for the records in MongoDB.

Here is a code to show all the records present in the collection.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
    if(err) {
       console.log(err);
       process.exit(0);
    }
    var dbo = db.db('codeforgeek');
    console.log('database connected!');
    var collection = dbo.collection('users');
    collection.find().toArray((err, results) => {
        if(err) {
            console.log(err);
            process.exit(0);
        }
        console.log(results);
        db.close();
    });
});

This code will retrieve all the records from the collection and print it on the terminal.

You can also add search parameters to help you find specific documents. Just change the query to this:

    collection.find({name: 'shahid'}).toArray((err, results) => {
        if(err) {
            console.log(err);
            process.exit(0);
        }
        console.log(results);
        db.close();
    });
Update the document in the collection

You can update the existing document using updateOne() function. The first parameter is for searching the document and second is for updating it with new values. Here is the snippet.

collection.updateOne({name: 'Shahid'}, {'$set': {'name': 'Shahid Shaikh'}}, (err, results) => {
    if(err) {
        console.log(err);
        process.exit(0);
    }
    console.log(results);
    db.close();
});
Delete the document in the collection

You can delete the existing documents in the collection using deleteOne() function.

collection.deleteOne({name: 'Shahid'}, (err, results) => {
    if(err) {
        console.log(err);
        process.exit(0);
    }
    console.log(results);
    db.close();
});
Summary

As of now, we studied how to interact with the MongoDB using Node.js. We can take a step forward and build something awesome such as an online book store, REST API, etc.

Further Study

Build a RESTful API using Node and MongoDB
Server Side Pagination Using Node and Mongo
Getting Started With Node – Course

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Let’s code an API Rate Limiter which will throttle users based on the number of the API requests they are sending to the Server.

Introduction:

Imagine you are running a service where you have allowed your customers to call the public API’s to do the certain operation in your system but due to obvious reason you don’t want them to bombard your system with so many API calls at the moment.

To add a restriction like that, we need an API rate limiter which basically allows an only certain number of API request in a given time frame. For example, 1 API per second or 100 API calls per minute etc.

System requirement:

Our API rate limiter should work in the distributed environment hence consistency must be maintained across the concurrent requests.

The API rate limiter should have configurable option to change the number of API requests allowed by the system.

How rate limiting works:

Rate limiting is a process to define the rate and level of the particular resource that can be accessed by the consumers. We use throttling to monitor the requests and allowing the requests that are valid and in throttle limit.

For example:

Throttle limit is 3 API/sec.

So whenever the incoming requests come in, we check the existing record and see if the throttle is reached.

If throttle reached we return HTTP status code 429 with the message “too many requests”.

There are three different types of throttling:

  1. Hard throttling: The number of requests cannot reach the limit.
  2. Soft throttling: The number of requests can be allowed to exceed for certain percentage when the throttle limit reached.
  3. Dynamic throttling: In dynamic throttling, we allow the requests even if throttle reached if the resources are free and available.

In this article, we are going to code hard throttling.

Rate limiting algorithms:

There are two types of rate limiting algorithm:

  • Fixed window algorithm.
  • Sliding window algorithm.

In fixed window algorithm, the time frame of the API call is fixed. Let’s try to understand it with an example, say user John sAPIted consuming API at 12:00:00 and the rate limit for him is 5 API per minute so between 12:00:00 to 12:01:00 he can make 5 request API regardless of when he started the api consumption process.

In sliding window algorithm, the window time is considered from the start time of the API call instead of the fixed start time.

We are going to develop the fixed window algorithm for our use case just to keep the logic simple and easy to understand.

High level system design

Rate Limiter will be responsible for deciding which request will be served by the API servers and which request will be declined. Once a new request arrives, Web Server first asks the Rate Limiter to decide if it will be served or throttled. If the request is not throttled, then it’ll be passed to the API servers.

Algorithm:

Here are the steps that will be required to perform the rate limiting.

Let’s say our rate limiter allowing 10 requests per minute. So whenever a new request comes in, we need to do the following:

If the ‘UserID’ is not present in the Redis, insert it and set the ‘Count’ to 1 and ‘StartTime’ to the current time in Unix format, and allow the request.

Otherwise, find the record of the ‘UserID’ and if ‘CurrentTime – StartTime >= 1 min’, set the ‘StartTime’ to the current time and ‘Count’ to 1, and allow the request.

If ‘CurrentTime – StartTime = 10’, reject the request with status code 429.

Looks simple right! Let’s code.

Software requirements:

You need to install the following software in your system (if not already) before heading forward, the link will take you to the respective installation page.

  • Node.js
  • Redis
  • Postman ( or your favourite API testing tool)
  • Atom (Optional, any editor would work)
Creating Node Project

Create a new folder and switch to that folder using the command line. Initiate the Node project using the following command.

npm init --y

Now, run the following command to install the dependencies required by the project.

npm i --S express redis moment

We are going to use the express module for the web server. Redis to store the rate-limiting information and moment to handle the time-related information.

Creating the Server

Here is the code piece of basic Server ready to serve API’s. We are using the express module to create the server.

app.js
const express = require('express')
const app = express()
const router = express.Router()
const rateCheck = require('./ratelimiter')

router.get('/',(req,res) => {
  res.send('<h1>API response</h1>')
})

app.use(rateCheck)
app.use('/api',router)

app.listen(3000)

In first three lines, I have declared the dependencies and created the instance of express and express router.

In the fourth line, I have included the file called ratelimiter.js which is actually the express middleware function. I will explain more about it in a minute.

We have created a very basic API which returns the response and added the middleware before the router so that rate limiter function executes every single time an API is been called.

Let’s look at the rate limiter code piece.

Creating Rate Limiter

Here is the code piece of rate limiter.

ratelimiter.js
const redis = require('redis')
const redisClient = redis.createClient()
const moment = require('moment')

module.exports = (req,res,next) => {
  redisClient.exists(req.headers.user,(err,reply) => {
    if(err) {
      console.log("Redis not working...")
      system.exit(0)
    }
    if(reply === 1) {
      // user exists
      // check time interval
      redisClient.get(req.headers.user,(err,reply) => {
        let data = JSON.parse(reply)
        let currentTime = moment().unix()
        let difference = (currentTime - data.startTime)/60
        if(difference >= 1) {
          let body = {
            'count': 1,
            'startTime': moment().unix()
          }
          redisClient.set(req.headers.user,JSON.stringify(body))
          // allow the request
          next()
        }
        if(difference < 1) {
          if(data.count > 3) {
            return res.json({"error": 1, "message": "throttled limit exceeded..."})
          }
          // update the count and allow the request
          data.count++
          redisClient.set(req.headers.user,JSON.stringify(data))
          // allow request
          next()
        }
      })
    } else {
      // add new user
      let body = {
        'count': 1,
        'startTime': moment().unix()
      }
      redisClient.set(req.headers.user,JSON.stringify(body))
      // allow request
      next()
    }
  })
}

Ok, let me explain.

The whole piece of code is divided into two important parts.

  1. If it’s the first request then add in the Redis and allow the request.
  2. If it’s a recurring request then check the request count and time difference and allow/disallow the request.

In first code block I am checking whether this user exists or not, if it exists then I am getting full information about the user from Redis and doing this:

Is the timestamp of the current request and timestamp of last recorded request in Redis is more than 1 minute? If so, then allow the request and reset the time in Redis.

If not, then check if the user has requested less than or equal to three requests? If it is less than three then allow the request.

If it’s more than three requests then disallow the request and return the response back.

Ok, enough talking. Let’s run the code.

Running the code

Switch to the folder of where you have placed the code using the terminal and run this command.

node app.js

And hit this API using POSTMAN or any other API simulator.

http://localhost:3000/api

Note: Make sure in headers you pass user key and some random value to it.

Or

Watch the video below to see how it works.

rate limier screenshot - YouTube

Summary

I hope you like this Codeforgeek pro article. This is the first entry and I am going to ship much more content like this, I am also thinking doing videos and audio on various topics.

Do let me know what you think about this article and how it can help you to decode the existing software and how they work.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

I have created one node package which i explained in previous tutorialThat package is published at Node package manager site and few people have downloaded that as well. In this tutorial i am going to explain how to create a NodeJS  NPM package and publish it at npmjs.org.

Before building the Node module you need some JavaScript skills. But let’s make it simple, we will develop one simple module which will take two numbers and operator(+,-,*,/) as input and print the result accordingly. Pretty simple to code in JS but let’s do it in Node.js.

Directory Structure :
----CFG npm module
--------package.json
--------lib
--------------index.js

Yes this is it. Our main code will be living at index.js file. Let us create the package.json file because for Node module it is very very important.

Creating Package.json :

Here is package.json file which i have created for our node calculator.

{
"name": "nodecalc",
"version": "0.0.1",
"description": "This package will return addition of two numbers",
"main": "./lib/index.js",
"repository": {
"type": "git",
"url": "https://github.com/codeforgeek/nodecalc"
},
"keywords": [
"sweet-lstat"
],
"author": {
"name": "Shahid Shaikh"
},
"readme": "# Add two numbers (for learning purpose)nnDemo module for codeforgeek.com tutorialnn## Installnn npm install nodecalcnnn## APInn### -calc(a,b,p) n where, n a=number,nb=number,p=operator",
"readmeFilename": "README.md",
"dependencies": {},
"devDependencies": {},
"optionalDependencies": {},
"engines": {
"node": "*"
},
"bugs": {
"url": "https://github.com/codeforgeek/nodecalc/issues"
},
"homepage": "https://github.com/codeforgeek/nodecalc",
"_id": "nodecalc@0.0.1",
"scripts": {},
"_shasum": "db9a913c2f8893d477472647917493f2c0949adb",
"_from": "nodecalc@"
}

I am sure you will say WTF is this. You will come to know the importance of each lines when we publish the app. Now let’s move ahead and create simple module in JavaScript which accept two number and operator and return the result.

Coding the actual module : NodeCalc

Create new file as “index.js” in lib folder and place this code in it.

var calc=function(a,b,p) {
    if(a==="" || b==="" || p==="") {
        return "Please provide all parameters";
    }
    switch(p) {
        case '+': {
            return a+b;
            break;
        }
        case '-': {
            return a-b;
            break;
        }
        case '*': {
            return a*b;
            break;
        }
        case '/': {
            return a/b;
            break;
        }
        default:{return;}
    }
}
exports.calc=calc; //very important line

You know what this is it. Now what we need to do is to publish this module at Node repository.

Publish Package to NPM:

First go to npmjs.org and create new account. Its simple and easy. Once you do it, open up your terminal and type following command.

sudo npm adduser

It will ask your user name, password and email. You can even create new account from here too. But doing it before is helpful. Here is screen shot for help.

Once you did this step. What you need to do is publish it.

sudo npm publish

After this step here is my module page at npmjs.org.

Installing Nodecalc module and testing it:

Let’s test our module. Create any folder and switch to that folder using terminal and type.

npm install --save nodecalc

Once done check whether node_modules is created on working folder or not. It should be there, now create any JS file and paste following code.

var math=require("nodecalc");
console.log(math.calc(10,20,'+'));
console.log(math.calc(20,10,'-'));
console.log(math.calc(10,20,'*'));
console.log(math.calc(20,2,'/'));

Run it using node and you should get following output.

If you are facing some error, you might need to check whether the “nodecalc” module is been installed correctly or not.

Edit published Module at NPM:

Suppose you want to update some information about this module, so what you need to do is unpublish the module, change the proper information for.eg Readme information and then change version number ( This is very important else you will face error)  and then publish it again.

Unpublish the module:

In case you want to update the module information or simply delete it from npm registry, all you need to do is.

npm unpublish

from the working folder. That’s it.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Facebook Login is widely used as an authentication module on websites. Instead of asking user manual details such as email and password and then verify them, it’s better to use already verified user details.

In this article, we are going to learn and implement a Facebook Login System using Nodejs and ExpressJS. You can download the code by clicking the button below.

DOWNLOAD

Creating Facebook App:

Very first thing you going to need is AppID and AppSecret from Facebook App. Please go to Facebook Developers and create your app.

Choose Website as platform when it ask. Give the proper name and you can leave the namespace field blank.

It will ask for Captcha, enter it carefully and once done it will redirect you to the app page. By authenticating your facebook account again you can view the App secret. Now go to Setting and add the Web as a platform.

If you want to test the app in localhost environment then add localhost:3000 as an site address.

The app is set. Let’s go ahead and create our App using Node.

Configuring our Node App:

In the source directory go to the configuration/config.js and update the Facebook AppID and AppSecret. If you want to use Database to store and validate user information you can put the configuration field as true or false. To know the database design for the app please visit twitter login using node article.

configuration/config.js
module.exports={
  "facebook_api_key"      :     "FB APP ID",
  "facebook_api_secret"   :     "FB API SECRET",
  "callback_url"          :     "http://localhost:3000/auth/facebook/callback",
  "use_database"          :      false,
  "host"                  :     "localhost",
  "username"              :     "root",
  "password"              :     "",
  "database"              :     "Database Name"
}

Update the code with Facebook App information.

Route of Our App:
Routes Action
/auth/facebook Authenticate User with Facebook
/auth/facebook/callback Get the user information from if login successfully
/logout Logging out from App.
Configuring Passport:

I am using Passport node package for the OAuth authentication. It requires configuration of some parameters. Here is our Passport configuration code.

app.js
/*config is our configuration variable.*/
passport.use(new FacebookStrategy({
    clientID: config.facebook_api_key,
    clientSecret:config.facebook_api_secret ,
    callbackURL: config.callback_url
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
      //Check whether the User exists or not using profile.id
      if(config.use_database) {
         //Further code of Database.
      }
      return done(null, profile);
    });
  }
));
Complete Server Code:

Here is our app.js with complete routing and Passport code.

app.js
const express         =     require('express')
  , passport          =     require('passport')
  , FacebookStrategy  =     require('passport-facebook').Strategy
  , session           =     require('express-session')
  , cookieParser      =     require('cookie-parser')
  , bodyParser        =     require('body-parser')
  , config            =     require('./configuration/config')
  , mysql             =     require('mysql')
  , app               =     express();

//Define MySQL parameter in Config.js file.
const pool = mysql.createPool({
  host     : config.host,
  user     : config.username,
  password : config.password,
  database : config.database
});

// Passport session setup.
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});


// Use the FacebookStrategy within Passport.

passport.use(new FacebookStrategy({
    clientID: config.facebook_api_key,
    clientSecret:config.facebook_api_secret ,
    callbackURL: config.callback_url
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
      //Check whether the User exists or not using profile.id
      if(config.use_database) {
        // if sets to true
        pool.query("SELECT * from user_info where user_id="+profile.id, (err,rows) => {
          if(err) throw err;
          if(rows && rows.length === 0) {
              console.log("There is no such user, adding now");
              pool.query("INSERT into user_info(user_id,user_name) VALUES('"+profile.id+"','"+profile.username+"')");
          } else {
              console.log("User already exists in database");
          }
        });
      }
      return done(null, profile);
    });
  }
));


app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'keyboard cat', key: 'sid'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});

app.get('/auth/facebook', passport.authenticate('facebook',{scope:'email'}));


app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { successRedirect : '/', failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});


function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}

app.listen(3000);
Designing our View:
index.ejs
<% if (!user) { %>
  <div style="width:500px;height:180px;">
    <h2 style="font-size:40px;">Welcome! Please log in.</h2>
    <a href="/auth/facebook"><img src="fb-login.jpg" width="151" height="24"></a>
    </div>
<% } else { %>
    <h2>Hello, <%= user.displayName %>.</h2>
<% } %>

Once user login we just have to show the values return from Facebook. Here it is.

<p>ID: <%= user.id %></p>
<p>Name :<%= user.displayName %></p>
Running our App:

Download the code and update the config.js with the Facebook app information. Then run

npm install

to install dependencies and then run app using

node app.js

Visit localhost:3000 to view the app.

Login using your Facebook account and allow the app permission. After successful authentication, you will be redirected to your specified callback URL.

Conclusion

We learned how to use and implement Facebook login system using Passport module. We used to express to develop the web server and MySQL to store user information.

Further Study

Learn more!
Twitter Login Using Node and MySQL
Facebook Status Box using Node.js and MySQL
HTML5 Push Notification System Using Nodejs MySQL Socket.io
How to Replace All Occurrences of a String in JavaScript

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Nodejs provides crypto modules to perform the encryption and hashing of sensitive information such as passwords. The Bcrypt node modules provides easy way to create and compare hashes.

Let’s learn how to use it.

Installation and usage

To use the library, simply install with NPM:

npm i --S bcrypt

Then include it in your project.

const bcrypt = require('bcrypt');
Creating and Verifying Hash

Bcrypt provides both synchronous and asynchronous methods. I recommend asynchronous method because hashing is CPU intensive, and the synchronous version will block the event loop and prevent your app from handling other requests until it finishes.

Here is the code for hashing using asynchronous method. First argument is the password and second argument is number of rounds for the salt generation.

To verify the hashed password you can use the following code:

That’s it. Easy as cake.

Conclusion

You must always hash your password or any sensitive information that you don’t need in original form again. Hashing is one way that means you can’t get the original data back from the hash but regenerate same hash using the original data.

Further Study

How to Validate an Email Address in JavaScript
How to Remove a Particular Element from an Array in JavaScript
How to Use Session Storage API in JavaScript
How to Replace All Occurrences of a String in JavaScript

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Introduction

In this article, we are going to cover the development and deployment of the Nodejs App on the Clouding.io platform. Clouding.io is the Cloud VPS service that offers affordable, SSD based virtual private servers to host your application.

Why Clouding Platform

Clouding.io has affordable virtual private servers with very fast processors, wide bandwidth and SSD for fast processing. Clouding.io aims to be the most efficient virtual private servers provider with cutting edge technology.

Some of the eye-catching features are:

  • Affordable price range:
  • You can start using Clouding.io for around 3 Euros ( 3.8 USD ) a month that will give you 1 GB of RAM and 5 GB SSD disk storage.

  • 3X Replica
  • Clouding.io keeps 3 copies of your cloud servers. If one fails, another one is started automatically on different hardware, so you don’t even realize about the issue. This allows a high-availability platform.

  • Anti-DDoS
  • Clouding.io uses various security measures to keep intruders away from your system. It detects untrustworthy IP addresses and applies the prevention mechanism from connecting to your Server.

  • SSD Drives
  • While most of the cloud servers charge extra bucks for SSD and normal drives, Clouding.io uses SSD by default. It speeds up the read/write of the data hence increasing the efficiency of your application.

    To learn more about the Clouding.io features, click here.

    Enough about features and price, let’s build one app and deploy it on the Clouding.io platform.

Let’s build our app!

Building Node App

Let’s build our app. We are going to build a sample form where user can submit details and verify the user using Google recaptcha.

Here are the steps we’ll take to develop this program:

  • Submit form using Ajax.
  • Get the google response key in Node.js Server.
  • Reverify the key and give the response to UI.

To submit the form using Ajax we will use jQuery.form library. For Server, we will use Express and for HTTP calls we will use request.

Create a new directory and create your Node project using the following command.

npm init --y

Let’s install the dependencies

npm i --save express request body-parser

To integrate Google reCAPTCHA in your web application, we need to first get the authorization keys. Click here to visit the Google reCAPTCHA website.

After logging in, add your website details.

After registration Google will provide you the following :

1: Site key.
2: Secret key.

Here is the HTML code to generate a simple form with Google reCAPTCHA.

<html>
  <head>
    <title>Google recapcha demo - Codeforgeek</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action='/submit' method="post">
      <input type="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <div class="g-recaptcha" data-sitekey="--paste your site key here--"></div><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
    </form>
  </body>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
  <script>
   // Will put our custom code here.
  </script>
</html>

Here is our JavaScript code to perform Ajax form submit.

  <script>
    $(document).ready(function() {
      $('#comment_form').submit(function() {
        $(this).ajaxSubmit({
          error: function(xhr) {
            status('Error: ' + xhr.status);
          },
         success: function(response) {
          console.log(response);
         }
        });
        //Very important line, it disable the page refresh.
        return false;
      });
    });
  </script>

Add this code right after loading the scripts in HTML page.

Here is our Nodejs code.

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const router = express.Router();
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));

router.get('/',function(req,res) {
  // Sending our HTML file to browser.
  res.sendFile(__dirname + '/index.html');
});

router.post('/submit',function(req,res){
  // g-recaptcha-response is the key that browser will generate upon form submit.
  // if its blank or null means user has not selected the captcha, so return the error.
  if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) {
    return res.json({"responseCode" : 1,"responseDesc" : "Please select captcha"});
  }
  // Put your secret key here.
  var secretKey = "--paste your secret key here--";
  // req.connection.remoteAddress will provide IP address of connected user.
  var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + req.body['g-recaptcha-response'] + "&remoteip=" + req.connection.remoteAddress;
  // Hitting GET request to the URL, Google will respond with success or error scenario.
  request(verificationUrl,function(error,response,body) {
    body = JSON.parse(body);
    // Success will be true or false depending upon captcha validation.
    if(body.success !== undefined && !body.success) {
      return res.json({"responseCode" : 1,"responseDesc" : "Failed captcha verification"});
    }
    res.json({"responseCode" : 0,"responseDesc" : "Sucess"});
  });
});

// This will handle 404 requests.
router.use("*",function(req,res) {
  res.status(404).send("404");
})

app.use('/', router);

// lifting the app on port 3000.
app.listen(3000);

Let’s test the app. Run it using the following command.

node app.js

And visit localhost:3000 to view the app.

Awesome! Let’s push this code in the Github repository. Create a new Github repo and execute the following command to push your code in the Github.

git init
git add .
git commit -m “first push”
git remote add origin << github repo URL >>
git push origin master

Once it is pushed to the Github repository, let’s deploy it in Clouding Server.

Hosting the App

Visit the Clouding.io website and signup with your email account. Once your account is verified, you can test the server with free credit for 5 Euros.

In the Clouding.io portal, click on the server creation button.

Choose the operating system and server configuration and click on the Submit button once done.

Clouding will then create a new Server and once it is ready you should see the status as active.

Click on the Server you want to access and you should see the details in the settings section.

Open up your terminal and SSH into it.

ssh username@yourserver IP

Then enter the password.

Let’s update the server.

sudo apt-get update

Let’s install Git.

sudo apt-get install git

Let’s install Nodejs.

curl -sL https://deb.nodesource.com/setup_11.x | sudo -E bash -
sudo apt-get install -y nodejs

Let’s install PM2.

npm i -g pm2

Let’s clone the project.

git clone << your github url >>

Switch to the project directory and install the dependencies.

npm install

Then run the app using the following command.

pm2 start app.js

Now visit your Server URL and you should see the app running.

Congratulations! You have hosted your Node app on a Clouding.io Server.

Conclusion

Clouding.io is one of the affordable and cutting edge cloud services I have tested and tried. Give this service a try and you won’t regret it. We have also learned how to create and deploy a fresh app to our virtual private server created on Clouding.io.

Further Study

How to Check If a File Exists in Node.js
Node.js MySQL Tutorial
Top 5 Must Have Visual Studio Code Extensions

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Codeforgeek | Node.js tutorials by Shahid (unixroot) Shaikh - 1M ago

We all love Ajax, don’t we? And there is an obvious reason. Ajax is great for user experience. In this tutorial, I am going to build an application using Node.js that will let the user upload files using Ajax instead of conventional upload that requires a browser refresh action to see the change.

LIVE DEMO DOWNLOAD
Recommended read : File uploads using node.js

Our application :

I am going to develop the same application as I have done in the last tutorial with some additional code changes which make it asynchronous or Ajax.

#1 : Handling global variable issue.
#2 : Upgrading to latest version of multer.

So we will use FORM submit and same Express router with multer middleware for handling file upload.

package.json
{
  "name": "file_upload",
  "version": "0.0.1",
  "dependencies": {
    "express": "4.13.3",
    "multer": "1.1.0"
  },
  "devDependencies": {
    "should": "~7.1.0",
    "mocha": "~2.3.3",
    "supertest": "~1.1.0"
  }
}

Switch to the folder where package file is saved and type

npm install

to install the dependencies.

Server.js
var express =   require("express");
var multer  =   require('multer');
var app     =   express();

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});

var upload = multer({ storage : storage}).single('userPhoto');

app.get('/',function(req,res){
      res.sendFile(__dirname + "/index.html");
});

app.post('/api/photo',function(req,res){
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

app.listen(3000,function(){
    console.log("Working on port 3000");
});
index.html
<html>
  <head>
    <title>File upload Node.</title>
  </head>
  <body>
      <form id="uploadForm"
         enctype="multipart/form-data"
         action="/api/photo"
         method="post">
      <input type="file" name="userPhoto" />
      <input type="submit" value="Upload Image" name="submit">
      <span id = "status"></span>
    </form>
  </body>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
</html>

If you have noticed we are using jquery.form library which allow us to do Ajax form submit. Have a look to JavaScript code.

index.html
<script>
  $(document).ready(function() {

     $('#uploadForm').submit(function() {
        $("#status").empty().text("File is uploading...");
        $(this).ajaxSubmit({

            error: function(xhr) {
        status('Error: ' + xhr.status);
            },

            success: function(response) {
        $("#status").empty().text(response);
                console.log(response);
            }
    });
        //Very important line, it disable the page refresh.
    return false;
    });    
});
</script>

On Form submit, we will stop the page refresh by returning FALSE and call the API using ajaxSubmit(). Add this code in separate file and add it below the jquery.form or copy and paste just below this line

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>

<script>
------Paste above code ------
</script>
Running the code :

Either download the ready made code from Github or save all those files in separate folder and switch to that folder using command prompt.

node Server.js

Visit localhost:3000 to view the app. Open chrome developer console or firebug console in order to see response from server.

Output :

Further Study

File uploads using Node.js
How to Upload Multiple Files Using Node.js
Node.js MySQL Tutorial

Conclusion:

Ajax always provides richness to the web application. jQuery.form is one of the stable and popular library. Multer takes care of handling multi-part data and provides ease to implementation.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Slack is without a doubt a widely adopted messaging tool. It’s been used in companies ranging from startups to fortune 1000. Slack offers various features such as integration, groups, private chat and bots.

Bots are one of the exciting features of slack for the developers. Slack offers SDK’s which we can integrate it into various programming languages.

In this tutorial, we are going to build one simple Slack bot that will fetch the latest currency exchange rates of various currencies whenever we ask for it.

Download Code

Prerequisites

You need Slack installed in your machine and slack workspace in place before proceeding ahead with the article. It’s really easy to set up the Slack and workspace. Just head over to Slack download page and download the latest version.

You need to have the latest Node.js installed in your system.

About Nodejs

Nodejs is a JavaScript runtime framework that allows us to execute JavaScript in the Server. Nodejs comes with asynchronous I/O and a single threaded execution system that allows programmers to write code that is free of deadlock and increases the I/O throughput of the overall system.

Related reading: Learn all about Node!

Node package manager or NPM, in short, is the package manager for Nodejs. Due to NPM, Nodejs has become an ecosystem and used by the front end, backend teams to develop the applications.

Head over toNode.js official site and download the latest stable version in your machine.

About Slack

Slack was originally meant to be the collaboration tool and it evolves into the complete ecosystem, thanks to the slack developer’s platform.

Slack allows developers to create bots that run on top of Slack. Majority of the companies such as Google, Pinterest has their bots available on Slack app directory, a repository of the slack bots.

Creating Slack Bot and getting API Keys

Go to Slack Developers page and register your application. Click here to create your new app on Slack developer registry.

Type in the name of your app and select the workspace.

Once your App is created, Slack will ask you to choose various features. Select the Bots feature.

Finish the creation of your app. After that click on OAuth and Permission button and authenticate your app. After authentication, Application tokens will be generated. We will use those values in our code.

Before moving ahead, install your app in your workspace. Click on Basic information under setting tab menu and then click on Install your app to your workspace.

Your app should be visible in your Slack like this.

Currency Exchange API

Now we have our bot ready with all the tokens we need for your code. Before that, we need to have a system that can get us real-time currency exchange data in a simple JSON format.

I am going to use currencylayer.com for this. They offer really great and easy to use API to fetch real time exchange data.

Related learning: Basic HTTP calls using Node.js

Head over to currency layer website and create your account. Once your account is created, copy the access key. We will use it call currency layer API and get the latest currency exchange information in simple JSON format.

Building NodeJS App to communicate to bot

We need to write code to listen to commands coming from Slack bot and if it matches to our predefined command then call the currencylayer API to get latest currency exchange data.

The predefined command would be report. So when we type report in our slack bot, it will do its job else ignore.

In simple steps, our Node.js code should do the following:

  1. Listen to the slack messages and filter out the text message (excluding media messages).
  2. Check if the user types the command report as an exact match in the message. We don’t want our code to react whenever someone types report in general messages.
  3. If the user has requested the currency report, then our code should call the currencylayer API and format the response.
  4. Our code should send the formatted response back to the user as a Slack message.

Enough talking, let’s head over to the code.

First, create a fresh directory and initialize Nodejs project using the following command.

npm init --y

Then install the following dependency.

npm i --S slackbots request

Then create a file and name it config.js and copy paste the following code in it.

config.js
module.exports = {
    slack: {
        token: '<copy Bot User OAuth Access Token from Slack API dashboard>',
        channelName: 'general' // change it other channel if you want
    },
    currencyLayer: {
        apiKey: '<currency layer api key>',
        apiEndPoint: 'http://apilayer.net/api/live?access_key=$ACCESS_KEY$',
        sourceCurrency: 'USD'
    }
}

Create a new file name it app.js and copy/paste the following code in it.

app.js
const SlackBot = require("slackbots");
const request = require("request");
const config = require('./config');

// initialize bot
const bot = new SlackBot({
    token: config.slack.token,
    name: "Currency Bot"
});

bot.on("start", () => {
    console.log("Bot is ready.");
});

// event raised when we type something on bot
// on each received message, filter it out
// the type 'message' is classified as a user-generated message

bot.on("message", (data) => {
    if(data.type==='message') {
        filterMessage(data)
    }
})

async function filterMessage(message) {
    // when user types report
    if(message.text === 'report') {
        let data = await getAllPair();
        let formattedData = "";
        Object.keys(data.quotes).forEach((singlePair) => {
            formattedData += singlePair;
            formattedData += ' : ' + data.quotes[singlePair] + '\n';
        })
        postMessage(formattedData)
    } else {
        // further processing can be done
        // such as custom commands
        return;
    }
}

function getAllPair() {
    return new Promise((resolve, reject) => {
        let apiEndPoint = config.currencyLayer.apiEndPoint.replace('$ACCESS_KEY$',config.currencyLayer.apiKey);
        request(apiEndPoint,(error,response,body) => {
            if(error) {
                return reject(error);
            }
            resolve(JSON.parse(body));
        })
    })
}

function postMessage(message) {
    bot.postMessageToChannel(config.slack.channelName, message);
}
Code explanation

We have stored our configuration details in a separate file named config.js. The code which does the magic is in app.js file.

We are listening to the events provided by the Slack API and on each message executing our function.

We have three important functions:

1: filterMessage(): In this function, we are checking whether the user has typed our command i.e report. If yes, then we are going to fetch the currency details using getAllPair() function and post the currency details to the Slack group using postMessage() function.

2: getAllPair(): In this function, we are calling the currencylayer API to fetch the latest currency exchange. We are using request node modules to achieve the same.

3: postMessage(): In this function, we are sending the message to the Slack group. The message is our currency exchange information.

In a nutshell, whenever you type something on the bot, an event will be generated and we can listen to that event in Nodejs using a simple event listener.

If the user has typed the predefined command, then we will call the currency layer API using our request module, parse the data and send it back to the Slack.

Running the code

Assuming you are using general channel name, invite your bot in the channel by typing @botname and hit enter.

Now run the app using the following command.

node app.js

Once a message is printed on the console saying ‘Bot is ready’ Like this.

Now in Slack, select your bot and type report. You should see the currency exchange data like this.

Try a few more commands and it won’t react because we have only configured the report command.

Deploying the Slack app

We have developed our Slack app and Node.js server. It’s time to let the world see it. In order to make it publicly accessible, we need to deploy the Slack app and deploy Node.js code.

In order to deploy the Slack app, we need to submit it to the Slack developer’s platform. In order to do so, open up the Slack app from slack apps page and go to Manage distribution section.

We need to perform the submission checklists and once everything is completed we can hit on Submit App button and your Slack app will be live. Install the app again in your workspace to update the app setting.

You can deploy the Nodejs app on Heroku platform in few clicks. Once everything is deployed, you can share the URL of your bot to the public and be ready for the feedback and appreciations.

Further reading Conclusion

Slack bots are really fun. We can develop amazing apps to help us automate lots of tasks while we do our work. For example, we can code Stack overflow bot that can look up the solution for us. We can build a simple bot to check weather and many more.

I hope you have learned bits and pieces of developing Slack bot using Nodejs.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview