Node.js

Node.js is a javascript framework used for writing server-client applications. Generally JS is used for client side scripting, i.e. front end but this is what makes node.js different from regular JS. It allows one to write the server side script using javascript. Node.js is used in the backend of many popular appplications like Linkedin, PayPal, Uber etc. Before going to the technicalities of Node.js, let's have a brief look at how a back-end application works.

Contents

Client-Server Model

Take an example of a simple school or college database querying system. Generally, you enter a roll number and you get the details corresponding to it. But, there are a lot of things going at the backstage. As you click the submit button after entering a roll number in the textbox, your browser (also called the client) sends a request to the server. As we are working with HTTP, this request is called the GET request. In response to this request, the server then sends a response to the browser, which is then displayed in the appropriate format on the screen. Have a look at this link to get a good idea about the generally used HTTP requests like PUT, POST, DELETE etc.

Nodejs.png

Soft Pre-Requisites

Assuming that you are familiar with basic HTML and JS, here are few more things that are extremely essential for developing node.js apps.

  • AngularJS: It is a JavaScript framework that allows you to extend HTML syntax quite flexibly according to your requirements. It is very commonly used with Node.js for displaying the response data as well sending the client requests to the server. Tutorialspoint or w3schools are great to start off with AngularJS.
  • RESTful APIs: API stands for application programming interface. It is kind of a black box, to which a browser sends a request and gets some response. REST APIs use HTTP requests (GET, POST, PUT, DELETE) for the client server interaction. For detailed information, refer to RESTful. We configure REST APIs in Node.js for enabling certain interactions of the client with the server. This would be very clear once we get to writing the APIs ourselves.
  • Asynchronous Functions: These are quite different from the functions we encounter normally. In general the functions we use, we can use their returned values directly. Such functions are called synchronous functions. Asynchronous functions don't return any value immediately, instead run a callback function, which passes the value or object produced by the asynchronous function after the execution into the main program. This ensures that the program doesn't stop waiting for the execution of just one function. Please refer this page for a simple and illustrative description of callback and asynchronous functions. It's a non-intuitive concept, but an extremely important one to understand to use Node.js effectively, as async functions are at the heart of Node.js.
  • Using Databases: As Node.js is a backend development application, it is extremely important to know how to use a database in order to incorporate it in our application. Commonly used databases with node.js are MongoDB and MySQL. Refer the following link for installing and using mysql. Make sure you can login to the mysql server using the command mysql -u root -p . Get a hang of using tables and databases, post which you can look up things as and when required.

Resources

  • The Udemy Blog: This blog is the most comprehensive and illustrative tutorial for Node.js we have found till now. It teaches you making an app to store and modify videos in a mongoDB database. Refer to this link for the awesome tutorial that awaits!. The tutorial also introduces you to the basics of mongoDB and Express. Express is a very handy framework for Node.js, which allows you to scaffold the basic setup of a project, which makes it very easy to work upon.

With all this information, you are ready to dive into the amazing world of possibilities. Once you complete the Udemy Blog tutorial, you will be develop many more apps according to your requirement.

So many new things at once may be trivial, but patience is the key. Whenever you fail to understand anything, just google it up. Once you get the hang of it, you will be able to make apps at your wish. I made a crowd sourced DR List Generator, with a mysql database as the backend. You can view the entire code on this github repo.

Using a MySQL Backend

There are very good resources on the internet about how to use mongoDB with node.js, but for mysql it was a bit of a struggle for me hence I decided to document mysql part of the DR List generator.

You can fork the project from this link. Make sure that your package.json file has a mysql dependency specified.

"dependencies": {
    "body-parser": "~1.15.1",
    "cookie-parser": "~1.4.3",
    "debug": "~2.2.0",
    "express": "~4.13.4",
    "jade": "~1.11.0",
    "mysql": "^2.11.1",
    "morgan": "~1.7.0",
    "serve-favicon": "~2.3.0"
  }
}

Run npm install on the terminal to install all the dependencies, if not installed. Refer to this code snippet in the app.js file.

var mysql = require('mysql');
 var connection = mysql.createConnection({ 
  host     : 'localhost', 
  user     : 'root', 
  password : '*******',
  database : 'DR_list'});

Line 1: Calls the dependency mysql as a variable 'mysql' in app.js.
Line 2:Initialises an object connection with the given specifications. DR_list is the name of the local database I used to store the required tables.

connection.connect(function(err) { 
if(!err) {
 	console.log("connected to database");
       }
else {
	console.log("error connecting to the database");
     }
});

Here we used the connect function of the object connection created earlier to establish a connection to the local database DR_list. It is an asynchronous function, as clear from the code. Now, as we are connected to the database, we can write APIs to query the database, or to modify it as we want. Navigate to /routes/insert.js in the DR_list folder. In the file insert.js

router.get('/:cpi/:roll_num', function(req, res) {
	var cpi = req.params.cpi;
	var roll_num = req.params.roll_num;
	console.log('entering into insert route');

	connection.query('INSERT INTO dr_table VALUES(' + connection.escape(cpi) + ',' + connection.escape(roll_num)+')', function(err,row,columns){
     if(!err)
       console.log('entered succesfully');     		
	});

	var obj = {
		roll_num : roll_num,
		cpi: cpi
	}
  res.json(obj);

});

This code fragment is the end point of the API /api/insert defined in app.js.

  • router.get('/:cpi/:roll_num', function(req, res) {
    Takes in the 2 values passed to this route, (cpi and roll_num in this case). It uses these values in the callback function with req (request) and res (response) as parameters.
  • connection.query('INSERT INTO dr_table VALUES(' + connection.escape(cpi) + ',' + connection.escape(roll_num)+')',.. This command is the query or operation to the database we want to perform. Its a simple mysql syntax for inserting values into a table (dr_table in this case).
  • connection.escape() is used to escape query parameters to avoid SQL injection attacks.

This query is also an asynchronous function, which on successfully executing the query print a console message.

In the file view_dr.js look at the following code fragment:

connection.query('SELECT * from dr_table where roll_no =' + connection.escape(roll_num), function(err,row,fields){
     cpi = row[0].cpi;
     console.log('cpi of the entered roll num is ' + cpi);
  
	connection.query('SELECT * FROM dr_table', function(err,rows,fields){
        size = rows.length;
        console.log(size);
	});

Here, the parameters of the call back function are the results of the query to the database. Hence, we can access the results of the query as shown in the code. row is an array of objects which contain the result of the query. try console.log(row) to see how the object looks like. row[0] is hence the first row the queried result, or rather the first row of the output of our query. One can refer the fields of the row as shown using the standard dot notation for objects. (The table dr_table has only 2 columns cpi and roll_no). The rest of the code is quite clear. One standard trick I follow to send the data to front end is, to convert the data into an object form and use the res.json() to send it. This makes it much easier to use the values with angular-JS in the front end. You would definitely enjoy joining the missing pieces of the puzzle by referring to the file script.js (/public/javascripts/script.js).

Conclusion

Node.js is an amazing scalable framework for developing fast web-apps. There are many more interesting things you can do with Node.js, like enabling authentication using passport.js, or using the node-mailer to configure sending mails automatically. This tutorial was meant to give you general idea of how to go about developing an app on node.js from scratch. I hope it served the purpose. You are most welcome to correct any kind of errors you find in this tutorial. Cheers!