Node.js

Node JS Basic Tutorial

This article provides a basic tutorial of NodeJs.Here, we will start with the simple NodeJs introduction and sample program and then leverage the discusion with the different modules such as HTTP, event, mysql, mongoDB available in NodeJs with the some simple use case and example code to make use of those modules in real time NodeJs application.

What is NodeJs

Node Js is an open source, cross-platform, non-blocking server side Javascript framework that has capabilities to execute javascript on the server. It is built on top of Google Chrome’s JavaScript Engine (V8 Engine).Here non-blocking means a node server does not wait till a response is served for any request rather it assigns a callback for any blocking operation such as DB operation and always ready to serve another request and whenever the blocking operation is completed the correspnding callback executes.Due to this architecture, Node Js is very fast and designed to handle huge number of requests asynchronously.

Create Node Js Server

You can visit the Node Js official website to download and install it or follow this link to set up on your local machine.

Following is the simple way to create a Node Js server.Node Js has a built in module called HTTP and using this module we can create Node server.Following sample creates a Node server that listens to HTTP request on port 8080. So, whenever a HTTP request comes to port 8080 Hello World response is sent back to the client.

var http = require('http');

http.createServer(function (req, res) {
  res.write('Hello World!');
  res.end(); 
}).listen(8080);

To execute above script you can save the file(sampleserver.js) containing above script on your local machine and execute it using following command.

node /Users/abc/nodesamples/sampleserver.js

Different Node Js Modules

Node Js has primarily 3 different modules – Core Module, Local Module and Third party Module. Core module is the module that is included in the Node Js binary distribution by default and load automatically when Node process starts. For example – http,url, queryString, path, fs etc. Similarly, local modules are custom modules created locally in our code. We generally include common application functionality in a local module for reuse.

Node Js Core Module

Core module is the module that is included in the Node Js binary distribution by default and load automatically when Node process starts.Different ore module provied by angular are http,url, queryString, path, fs

var module = require(‘http’); loads HTTP core module. Following is an example to work with url module provided by Node.

var http = require('http');
var url = require('url');

http.createServer(function (req, res) {
	var q = url.parse(req.url, true);
	console.log(q.host); //returns 'localhost:8080'
	console.log(q.pathname);
	console.log(q.search);

Above line prints the host, pathname and search parameter in the console.

Node Js Local Module

Local modules are custom modules created locally in our code to moduarise the common functionality such as following is a local module example that Date object.

datetimemodule.js

var datetime = {
            getDateTime : function () { 
                 return Date();
            }
    };

module.exports = datetime

This module can be included as – var dt = require(‘./datetimemodule.js’);

Node Js Events

Any action is an event and node provides event module to handle events.Node provides ways to either create your own event using events module or can use exiting events on any node object such as following is an example to raise event on opening and closing a file.

var fs = require('fs');
var rs = fs.createReadStream('./file.txt');
rs.on('open', function () {
  console.log('File is opened.');
});

It is also possible to create a custom event in Node.Following is an example to raise and handle custom event.

var events = require('events');

var em = new events.EventEmitter();

//Subscribe for myEvent
em.on('myEvent', function (data) {
    console.log('My first event raised - ' + data);
});

// Raising myEvent
em.emit('myEvent', 'This is my first event.');

In the above example whenever myEvent is raised, the log will be printed in the console.

MySQL Database Access in NodeJs

Firt, we require to install mysql driver to access a MySQL database from node application. To install MySQL driver, run following command

npm install mysql

Once this is done, you can include this mysql module in you existing js file to connect to a database and execute sample query.

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "root"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  con.query("sqlString", function (err, result) {
    if (err) throw err;
    console.log("Result: " + result);
});

 

MongoDB Access in NodeJs

npm install mongodb installs driver for mongoDB in node and once this is done we can use this module to communicate with the MongoDB database.Following is an example to connect to testdb and fetch user.

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/testdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("testdb");
  dbo.collection("users").findOne({}, function(err, result) {
    if (err) throw err;
    console.log(result.name);
    db.close();
});

Conclusion

I hope this tutorial helped in building basic idea of Node Js. In the next tutorial, we will look into configuring express.js with node for API development.If you have anything that you want to add or share then please share it below in the comment section.

Published on Web Code Geeks with permission by Dhiraj Ray, partner at our WCG program. See the original article here: Node JS Basic Tutorial

Opinions expressed by Web Code Geeks contributors are their own.

Dhiraj Ray

He is a technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. He is an avid reader and a technology enthusiast who likes to be up to date with all the latest advancements happening in the techno world. He also runs his own blog @ devglan.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button