Loading...

Follow CronJ Blog | Node.js on Feedspot

Continue with Google
Continue with Facebook
or

Valid
CronJ Blog | Node.js by Chandra Sekhar Ch - 1w ago

In this article, we will learn how to do database operations like create, update, insert, delete with Nodejs Mysql database and NodeJs application.

Before we go into the coding part, let’s get a brief introduction about Node.js and MySQL technologies.

Node Js: It‘s a platform built on Chrome’s JavaScript runtime for scalable network applications and easily building and fast building applications. It’s an open-source platform which will execute server-side javascript code.  

MySQL: MySQL is an open-source RDBMS (Relational Database Management System) that uses SQL(Structured Query Language). It is the most popular language for doing multiple operations with the database. So, In this blog, we will use MySQL as a database for node application.

NodeJS MYSQL tutorial prerequisites:

Before you join in this tutorial it is assumed that you meet requirements below.

* Make sure that Node Js has installed on your system.

* Understanding on basic Node JS and Express JS.

* Knowledge on SQL queries.

* I recommend you to install xampp on your system.

Node.js and MySQL are one of the necessary binding needed for the development of web applications.

MySQL is one of the most popular open-source databases, and it is efficient as well.

Almost every popular programming language provides a driver to access and perform operations with MySQL.

Now, let’s move to the NodeJS MYSQL coding part:Step 1:

Make a directory for our application

$ mkdir nodeMySQL

$ cd nodeMySQL
Step 2:

Now, we will generate package.json, so that all dependencies can be listed. Run the following command.

$ npm init

Step 3:

Now install all the required modules.

Express:
$ npm install express
Body-parser:
$ npm install body-parser
Express-session:
$ npm install express-session
MYSQL:
$ npm install mysql
Nodemon:
$ npm install nodemon
Cors:
$ npm install cors
Step 4:

Now require all modules in index.js and start the server with 3000 port. Find below code of index.js

const express = require('express');

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

const session = require('express-session');

const cors = require('cors');

const mysql = require('mysql');

const { promisify } = require('util')



const app = express();

app.use(bodyParser.json());

app.use(session({

   secret : 'thesecret',

   saveUninitialized: false,

   resave : false

}));



router = express.Router({

   mergeParams: true

}), router.use(cors());

 

const startServer = async () => {

   const port = process.env.SERVER_PORT || 3000;

   await promisify(app.listen).bind(app)(port);

   console.log(`Listening on port ${port}`);

}

startServer();



module.exports = router;
MySQL Database Operations

Create Database:

To create a database, first we have to connect to the database and we can create a database using “CREATE DATABASE dbName” query. Please find the following code.

const conn = mysql.createConnection({

   host: "localhost",

   user: "root",

   password: "mypasswd"

});



conn.connect((err) => {

   if(err) throw err;

   /*Create Database name using "mydatabase" */

   conn.query("CREATE DATABASE mydatabase", (err, result) => {

       if(err) throw err;

       console.log("Database is created..");

   })

});

Create a Table:

Create a table with table name called users and make id as Int, primary key and auto_increment. Which will insert a unique number for each insert.  

const conn = mysql.createConnection({

   host: "localhost",

   user: "root",

   password: "mypasswd",

   database: "mydatabase"

});



conn.connect((err) => {

   if (err) throw err;

   console.log("Connected!");

   let createTableQuery = "CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255), address VARCHAR(255))";

   conn.query(createTableQuery, (err, result) => {

       if (err) throw err;

       console.log("Table created");

   })

});
Alter Table:

Now the table has created with table name called users. Now we want to add one more column for user table. Then we will use ALTER keyword and follow the code below.

const conn = mysql.createConnection({

   host: "localhost",

   user: "root",

   password: "mypasswd",

   database: "mydatabase"

});



conn.connect((err) => {

   if (err) throw err;

   console.log("Connected!");

   let createTableQuery = "ALTER TABLE users ADD COLUMN phone_number BIGINT(10)";

   conn.query(createTableQuery, (err, result) => {

       if (err) throw err;

       console.log("Table is altered..");

   })

});

Insert Into Table:

To fill data in a table, we have to insert data using INSERT INTO statement as follows.

const conn = mysql.createConnection({

   host: "localhost",

   user: "root",

   password: "mypasswd",

   database: "mydatabase"

});



conn.connect((err)=> {

   if (err) throw err;

   console.log("Connected!");

   let insertQuery = "INSERT INTO users (name, address, phone_number) VALUES ('Narendra Modi', 'India', '1090290987')";

   conn.query(insertQuery, (err, result) => {

       if (err) throw err;

       console.log("1 record inserted");

   })

})

Select From:

To select data from a table we use SELECT statement and please find the following code. Assume that we have 100 number of rows in the user table.

const conn = mysql.createConnection({

   host: "localhost",

   user: "root",

   password: "mypasswd",

   database: "mydatabase"

});



conn.connect((err) => {

   if (err) throw err;

   console.log("Connected!");

   let selectQuery = "SELECT * FROM `users`";

   conn.query(selectQuery, (err, result) => {

       if (err) throw err;

       console.log(result);

   })

});

Where:

Let’s take we have 120 rows in our user table. Now, we want to fetch the records name matches with Narendra then we will use WHERE clause in the query. Please find the following code.

const conn = mysql.createConnection({

   host: "localhost",

   user: "root",

   password: "mypasswd",

   database: "mydatabase"

});



conn.connect((err) => {

   if (err) throw err;

   console.log("Connected!");

   let selectQueryWhere = "SELECT * FROM `users` where name = 'Narendra Modi'";

   conn.query(selectQueryWhere, (err, result) => {

       if (err) throw err;

       console.log(result);

   })

})
ORDER BY:

After getting records using SELECT statement, now we want in order by ascending, then we will apply ORDER BY to the select query as follows.

const conn = mysql.createConnection({

   host: "localhost",

   user: "root",

   password: "mypasswd",

   database: "mydatabase"

});



conn.connect((err) => {

   if (err) throw err;

   console.log("Connected!");

   let selectQueryOrderBy = "SELECT * FROM `users` ORDER BY id asc";

   conn.query(selectQueryOrderBy, (err, result) => {

       if (err) throw err;

       console.log(result);

   })

})
Update:

Suppose we want to update a particular record with a particular matching columns rows, then we will use UPDATE statement as follows.

const conn = mysql.createConnection({

   host: "localhost",

   user: "root",

   password: "mypasswd",

   database: "mydatabase"

});



conn.connect((err) => {

   if (err) throw err;

   console.log("Connected!");

   let updateQuery = "UPDATE users SET address = 'America 123' WHERE address = 'India'";

   conn.query(updateQuery, (err, result) => {

       if (err) throw err;

       console.log(result);

   })

})
Delete:

Now if we want to delete a particular row or rows we can use DELETE statement as follows.

const conn = mysql.createConnection({

   host: "localhost",

   user: "root",

   password: "mypasswd",

   database: "mydatabase"

});



conn.connect((err) => {

   if (err) throw err;

   console.log("Connected!");

   let deleteQuery = "DELETE FROM `users` WHERE name='Narendra Modi'";

   conn.query(deleteQuery, (err, result) => {

       if (err) throw err;

       console.log(result);

   })

});

If you’ve any doubts, please let us know through comment!!

Follow Us on Facebook | Twitter | LinkedIn.

Let CronJ assist you..!

Thank you !!!

The post Hands–On with NodeJs MySQL appeared first on CronJ Blog.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
What is WebSocket?

Node Js WebSocket is a protocol and it makes two-way communication between the user and the server in real-time. Websockets are an alternative for HTTP communication in web applications.

WebSockets offer bidirectional communication between client and server and Node Js WebSocket makes it possible to open an interactive communication between user’s browser and server to send messages to the server and it receives event-driven responses without having to poll the server for a reply.

Once the connection is established, then the channel is kept open, offering very fast connection with low latency and overhead.

Common use cases are chats, Online multiplayer games, Google Docs, etc.

To work with the Node Js WebSocket API for asynchronous communication between browser and servers, Here are some libraries in Node.js

  • WebSocket
  • Ws
  • Socket.io
  • Sockjs
  • Socketcluster
  • WebSocket as promised
Chat Features:

The beginning an user can select their name and the server will assign them some random color and will post some system message to the console that a new user was connected.

Then the user can post messages. When the user closes the browser window, the server will post another system message to the console that a user has disconnected. And also, every new user will receive the entire message history.

Here find HTML + CSS Code:

<!DOCTYPE html>

<html>

   <head>

       <meta charset=”utf-8″>

       <title>WebSockets – Simple chat</title>

       <style>

           * {

               font-family:tahoma;

               font-size:12px;

               padding:0px;

               margin:0px;

           }

           p { line-height:18px; }

           div { width:500px; margin-left:auto; margin-right:auto;}

           #content { padding:5px; background:#ddd; border-radius:5px;

               overflow-y: scroll; border:1px solid #CCC;

               margin-top:10px; height: 160px; }

           #input { border-radius:2px; border:1px solid #ccc;

               margin-top:10px; padding:5px; width:400px;

           }

           #status { width:88px;display:block;float:left;margin-top:15px; }

       </style>

   </head>

   <body>

       <div id=”content”></div>

       <div>

           <span id=”status”>Connecting…</span>

           <input type=”text” id=”input” disabled=”disabled” />

       </div>

       <script src=”//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js”></script>

       <script src=”frontend.js”></script>

 </body>

</html>

client → server, server → client communication:

For client →server communication I choose simple text because it is not necessary to wrap it in a more complicated structure.

When some user sends a message i.e client → server and then the server sends that message to all connected users i.e server →client.

But for the server –> client it’s a bit more complex. We have to separate steps into 3 different types of message:

  • The server assigns a color to the user
  • The server sends entire message history
  • The server broadcasts a message to all users

Therefore every message is a JavaScript Object encoded into JSON.

In this blog I am going to use the Node Js WebSocket library, so let us install with

$ npm install websocket

Then your code:

var WebSocketServer = require(‘websocket’).server;

var WebSocketClient = require(‘websocket’).client;

var WebSocketFrame  = require(‘websocket’).frame;

var WebSocketRouter = require(‘websocket’).router;

var W3CWebSocket = require(‘websocket’).w3cwebsocket;

Node Js WebSocket example code:

const WebSocketServer = require(‘websocket’).server;

const http = require(‘http’);

const server = http.createServer(function(request, response) {

   // process HTTP request. Since we’re writing just WebSockets

   // server we don’t have to implement anything.

});

server.listen(4040, function() { });

// create the server

wsServer = new WebSocketServer({

   httpServer: server

});

// WebSocket server

wsServer.on(‘request’, function(request) {

   var connection = request.accept(null, request.origin);

   // This is the most important callback for us, we’ll handle

   // all messages from users here.

   connection.on(‘message’, function(message) {

       if (message.type === ‘utf8’) {

           // process WebSocket message

       }

   });

   connection.on(‘close’, function(connection) {

       // close user connection

   });

});

Client-side basically we need three callback:

$(function () {

           // if user is running mozilla then use it’s built-in WebSocket

           window.WebSocket = window.WebSocket || window.MozWebSocket;

           var connection = new WebSocket(‘ws://127.0.0.1:4040’);

           connection.onopen = function () {

           // connection is opened and ready to use

           };

           connection.onerror = function (error) {

           // an error occurred when sending/receiving data

           };

           connection.onmessage = function (message) {

           // try to decode json (I assume that each message

           // from server is json)

           try {

             var json = JSON.parse(message.data);

           } catch (e) {

             console.log(‘This doesn\’t look like a valid JSON: ‘,

                 message.data);

             return;

           }

           // handle incoming message

           };

       });

Client-side chat source code:

$(function () {

           “use strict”;

           // for better performance – to avoid searching in DOM

           var content = $(‘#content’);

           var input = $(‘#input’);

           var status = $(‘#status’);

           // my color assigned by the server

           var myColor = false;

           // my name sent to the server

           var myName = false;

           // if user is running mozilla then use it’s built-in WebSocket

           window.WebSocket = window.WebSocket || window.MozWebSocket;

           // if browser doesn’t support WebSocket, just show

           // some notification and exit

           if (!window.WebSocket) {

           content.html($(‘<p>’,

             { text: “Sorry, but your browser doesn’t support WebSocket.” }

           ));

           input.hide();

           $(‘span’).hide();

           return;

           }

           // open connection

           var connection = new WebSocket(‘ws://127.0.0.1:4040’);

           connection.onopen = function () {

           // first we want users to enter their names

           input.removeAttr(‘disabled’);

           status.text(‘Choose name:’);

           };

           connection.onerror = function (error) {

           // just in there were some problems with connection…

           content.html($(‘<p>’, {

               text: ‘Sorry, but there\’s some problem with your ‘ + ‘connection or the server is down.’

           }));

           };

           // most important part – incoming messages

           connection.onmessage = function (message) {

           // try to parse JSON message. Because we know that the server

           // always returns JSON this should work without any problem but

           // we should make sure that the massage is not chunked or

           // otherwise damaged.

           try {

             var json = JSON.parse(message.data);

           } catch (e) {

             console.log(‘Invalid JSON: ‘, message.data);

             return;

           }

           // NOTE: if you’re not sure about the JSON structure

           // check the server source code above

           // first response from the server with user’s color

           if (json.type === ‘color’) {

             myColor = json.data;

             status.text(myName + ‘: ‘).css(‘color’, myColor);

             input.removeAttr(‘disabled’).focus();

             // from now user can start sending messages

           } else if (json.type === ‘history’) { // entire message history

             // insert every single message to the chat window

             for (var i=0; i < json.data.length; i++) {

             addMessage(json.data[i].author, json.data[i].text,

                 json.data[i].color, new Date(json.data[i].time));

             }

           } else if (json.type === ‘message’) { // it’s a single message

             // let the user write another message

             input.removeAttr(‘disabled’);

             addMessage(json.data.author, json.data.text,

                        json.data.color, new Date(json.data.time));

           } else {

             console.log(“Hmm…, I have never seen JSON like this:”, json);

           }

           };

           /**

           * Send message when user presses Enter key

           */

           input.keydown(function(e) {

           if (e.keyCode === 13) {

             var msg = $(this).val();

             if (!msg) {

               return;

             }

             // send the message as an ordinary text

             connection.send(msg);

             $(this).val(”);

             // disable the input field to make the user wait until server

             // sends back response

             input.attr(‘disabled’, ‘disabled’);

             // we know that the first message sent from a user their name

             if (myName === false) {

               myName = msg;

             }

           }

           });

           /**

           * This method is optional. If the server wasn’t able to

           * respond to the in 3 seconds then show some error message

           * to notify the user that something is wrong.

           */

           setInterval(function() {

           if (connection.readyState !== 1) {

             status.text(‘Error’);

             input.attr(‘disabled’, ‘disabled’).val(

                 ‘Unable to communicate with the WebSocket server.’);

           }

           }, 3000);

           /**

           * Add message to the chat window

           */

           function addMessage(author, message, color, dt) {

           content.prepend(‘<p><span style=”color:’ + color + ‘”>’

               + author + ‘</span> @ ‘ + (dt.getHours() < 10 ? ‘0’

               + dt.getHours() : dt.getHours()) + ‘:’

               + (dt.getMinutes() < 10

                 ? ‘0’ + dt.getMinutes() : dt.getMinutes())

               + ‘: ‘ + message + ‘</p>’);

           }

       });

WebSocket server side code:

“use strict”;

process.title = ‘node-chat’;

const webSocketsServerPort = 4040;

const webSocketServer = require(‘websocket’).server;

const http = require(‘http’);

var history = [ ];

var clients = [ ];

function htmlEntities(str) {

   return String(str)

   .replace(/&/g, ‘&amp;’).replace(/</g, ‘&lt;’)

   .replace(/>/g, ‘&gt;’).replace(/”/g, ‘&quot;’);

}

var colors = [‘purple’, ‘plum’, ‘orange’, ‘red’, ‘green’, ‘blue’, ‘magenta’ ];

colors.sort(function(a,b) {

   return Math.random() > 0.5;

});

var server = http.createServer(function(request, response) {

 

});

server.listen(webSocketsServerPort, function() {

   console.log(” Server listening port ”  + webSocketsServerPort);

});

var wsServer = new webSocketServer({

   httpServer: server

});

wsServer.on(‘request’, function(request) {

   console.log(‘ Connection origin ‘ + request.origin + ‘.’);

   var connection = request.accept(null, request.origin);

   

   var index = clients.push(connection) – 1;

   var userName = false;

   var userColor = false;

   console.log(‘ Connection is accepted.’);

   

   if (history.length > 0) {

       connection.sendUTF(JSON.stringify({ type: ‘history’, data: history} ));

   }

 

  connection.on(‘message’, function(message) {

   if (message.type === ‘utf8’) {

       

       if (userName === false) {

           

           userName = htmlEntities(message.utf8Data);

           

           userColor = colors.shift();

           connection.sendUTF(

               JSON.stringify({ type:’color’, data: userColor }));

           console.log(‘ User is known as: ‘ + userName + ‘ with ‘ + userColor + ‘ color.’);

         } else {

           console.log(‘ Received Message from ‘ + userName + ‘: ‘ + message.utf8Data);

           

           var obj = {

             time: (new Date()).getTime(),

             text: htmlEntities(message.utf8Data),

             author: userName,

             color: userColor

         };

         history.push(obj);

         history = history.slice(-100);

           

           var json = JSON.stringify({ type:’message’, data: obj });

           for (var i=0; i < clients.length; i++) {

             clients[i].sendUTF(json);

         }

     }

   }

   });

   

   connection.on(‘close’, function(connection) {

   if (userName !== false && userColor !== false) {

       console.log(connection.remoteAddress + ” was disconnected.”);

       

       clients.splice(index, 1);

       

       colors.push(userColor);

   }

   });

});

Now run the server script. Now you can open your HTML, if everything works fine it should ask your name to print in the console.

If you like what we are doing, please follow Us on Facebook | Twitter | LinkedIn.

Let CronJ Assist You..!

Thank You.

The post Node JS WebSocket: Examples | Chat Features | Client-Server communication appeared first on CronJ Blog.

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

Node.js is a server-side scripting language based on Google’s V8 Javascript engine. Node js is a single-threaded and highly scalable system. Instead of separate processes and threads, it uses asynchronous, event-driven I/O operations. So It can achieve high output via single-threaded event loop and non-blocking I/O.

Why Node Js is single-threaded?

Node.js is single-threaded for asynchronous processing. By doing asynchronous processing on a single-thread under typical web loads, more performance and scalability can be achieved.

What is Non-blocking or asynchronous?

A non-blocking operation will not wait for I/O operation to complete.

When blocking operation caused the process to be put on the back burner at the operating system level, performing a non-blocking I/O operation the process continues to run instead.

A non-blocking call initiates the operation, leaves it for the operating system to complete returning and immediately without any results.

Alternate means are then used to determine the completion of the I/O operation.

There are a few ways to communicate that non-blocking I/O operation has been completed.

Programs interacting closer with operating systems that use polling.

By using polling, the program repeatedly asks from the operating system that has any I/O operation to complete? and then process those operations have. In Javascript, we can also do with callbacks.

A non-blocking call in JavaScript, that provides a callback function that is to be called when the operation is completed.

Node.js was internally used operating system level polling in combination with worker threads for operations that do not support polling.

Then node.js translates these mechanisms to callbacks.

A performant application uses non-blocking I/O operations.

This allows a single process to serve multiple requests at the same time.

Instead of no of processes being blocked and waiting for a single I/O operation to complete, this waiting time can be used to serve other requests.

All Node.js libraries and the Node.js core API offer non-blocking operations.

For your reference please have a look at the image.

Let us take a real-time example,

Eg:

When you went to a restaurant, the waiter comes to your table, takes your order and gives it to the kitchen.

Then he moved to serve another table.

While the chef is preparing your meal, so the same person can serve many different tables.

They don’t have to wait for the chef to cook one meal before they serve another table.

This is called non-blocking or asynchronous architecture and this is how node applications work.

Example for non-blocking:

Let’s take a file name called sample.txt. It contains only “Hello World..”.

Write a snippet in another file:

const fs = require(‘fs’);  // Require the fs library

console.log(“Execution started..”);  

// File I/O Operation

fs.readFile(‘file.txt’, function(err, data){

if(err) {

return console.error(err);

}

console.log(data.toString());

});

console.log(“Execution Ended..”);

If you run node server you will get the following output.

What is Blocking or synchronous?

Once again let’s go back to our restaurant example.

Eg:

Imagine you went to another restaurant. A waiter is allocated to you. You gave an order to him.

Now the waiter went to the kitchen and give orders to the chef, and now he is sitting ideal while preparing your order.

That means now the waiter here acting like a thread.

He will go to the next order after delivering your order.

While preparing your order your thread (waiter) is waiting for the response.

This is called blocking or synchronous architecture and that’s how applications built with frameworks like a speed net or rails work out of the box.

So a thread is allocated to handle that request when we receive a request on the server as a part of handling that request.

It is likely that we’re going to query a database and as you know sometimes it may take a little while until the result is ready.

When the database is executing the query that the thread is waiting ideally, it can’t be used to serve for another client.

So we need another new thread to serve another client.

Imagine what would happen if we have a large number of parallel clients at some point we are going to run out of threads to serve these clients.

For your reference please have a look at the image.

Example for blocking:

var contents = fs.readFile(‘file.txt’,’utf8′, function(err,contents){

     console.log(contents);

});

var contents = fs.readFile(‘file1.txt’,’utf8′, function(err,contents){

      console.log(contents);

});

This will give you the output:

Is it possible to use asynchronous architecture?

So with this kind of architecture, we are not utilizing our resources efficiently.

This is the problem with synchronous or blocking.

In previous examples as I explained that’s how applications built with frameworks like asp.net worked by default. Of course in asp.net, it is possible to use asynchronous architecture.

To handle all requests we have a single thread, the linear request arrives that a single thread is used to handle that request.

If you need to query a database our single thread doesn’t have to wait for the database to return the data while the database is executing our query.

That thread will serve another client when the database prepares the result, it puts a message in what we call an event queue.

In the background, the Node is continuously monitoring this queue.

When it finds an event in this queue it will take it out and will do the remaining process.

This kind of architecture makes the node ideal for building applications that include a lot of network access or disks.

We can serve more clients without the need to throw in more hardware and that’s why no applications are highly scalable in contrast.

The node should not be used for CPU intensive applications like image manipulation service or a video encoding.

In such applications, we have a lot of calculations that should be done by CPU and few operations that touch the file system or the network.

Since no applications are single threaded while performing the calculations to serve one client, other clients have to wait.

And that’s the reason, the node should not be used or CPU intensive applications.

It should only be used for building data-intensive and real-time applications.

Follow Us on Facebook | Twitter | LinkedIn.

Thank You.

The post Node Js: Non-blocking or asynchronous | Blocking or synchronous appeared first on CronJ Blog.

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