Basic Concepts of Node.js (Server Side JavaScript)

As Wikipedia states: “Node.js is a packaged compilation of Google’s V8 JavaScript engine, the libuv platform abstraction layer, and a core library, which is itself primarily written in JavaScript.” Beyond that, it’s worth noting that Ryan Dahl, the creator of Node.js, was aiming to create real-time websites with push capability, “inspired by applications like Gmail”. In Node.js, he gave developers a tool for working in the non-blocking, event-driven I/O paradigm.

In this post i will demonstrate some of the basic concepts of Node.js using which you can start server side coding using javascript.this tutorial assume you have a basic knowledge of javascript. please install node.js in your system prior going through the code snippets below. once you have the environment setup save the code in “[Name].js” and to run it open the command prompt and type the following command
node [Name].js as simple as that.

The below code demonstrate how to open a file from the file system and displaying its statistics. also the below code tells the given file is a file or not.

var fp = require("fs");

/**
 * getting file statistics. 
 */
fp.stat('NodeTestFile.txt',function(error,stats){
	if(error){
		throw error;
	}else{
		console.log('NodeTestFile.txt is a file:'+stats.isFile());
		console.log(stats);
	}
});

now its time for us to read a file’s content in bytes and display it in console.

/**
 * reading file content in bytes.
 */
fp.open('NodeTestFile.txt','r',function(err,fd){
	if(err){
		throw err;
	}else{
		var readBuffer = new Buffer(1024);
		bufferOffset = 0;
		bufferLength = readBuffer.length;
		filePosition = 0;
		fp.read(fd,readBuffer,bufferOffset,bufferLength,filePosition,function read(err,readBytes){
			console.log('just read ' + readBytes + ' bytes');
			if (readBytes > 0) {
			console.log(readBytes);
			}
		});
	}
});

Now if we need to read the content from file and display it con console(not as bytes), below is the code

/**
 *	reading file content
**/
fp.readFile('NodeTestFile.txt',{encoding: 'utf-8'},function read(err,data){
	if(err){
		throw err;
	}else{
		console.log(data);
	}
});

as we are done with reading of file, lets us take a chance to write back to the file, please follow the below code to write the content to the file

/**
* Writing the content back to file
**/

fp.open('NodeTestFile.txt','a',function opened(err,fd){
	if(err){
		throw err;
	}else{
		var writeBuffer = new Buffer('content from Buffer'),
		bufferPosition = 0,
		bufferLength = writeBuffer.length,filePosition = null;
		fp.write(fd,writeBuffer,bufferPosition,bufferLength,filePosition,function wrote(err,data){
			if(err){
				throw err;
			}else{
				console.log("content written to file");
			}
		});
	}
});

so here ends our concepts on file handling, now ill show how to create simple http server using node.js.

/**
 * 
 */
var http = require('http');

http.createServer(function handler(req, res) {
		
	res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end("Hello Node JS\n");
    
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

once the above code is saved in file please run from command prompt and open the browser and hit the url you will be seeing “Hello Node JS” in the browser. there is little to take about the code above as you see the very first statement “require(‘http’)” is called the module loading by node.

so far we have covered node.js interacting with file system and http requests by creating http server, now its time for us to make node.js to interact with database.

/**
 * New node file, with database connectivity and handling
 */
var db = require('mysql');
var connection = db.createConnection({
	host : "localhost",
	user : "username",
	password : "password"
});

connection.connect(function(error, result) {
	if (error) {
		console.log('Connection Error: ' + error.message);
		return;
	}
	console.log('Connected to MySQL Database');
	clientReady(connection);
});

clientReady = function(connection) {
	connection.query("use test", function(error, result) {
		if (error) {
			console.log('Connection Error: ' + error.message);
			return;
		}
		console.log('Ready to fetch the results...');
		fetchResults(connection);
	});
};

fetchResults = function(connection) {

	var strQuery = "select * from country";
	connection.query(strQuery, function(err, rows) {
		if (err) {
			throw err;
		} else {
			console.log(rows);
		}
	});
};

thats all folks on the basics of node.js.
Happy coding Node.js 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s