Perfect Housewife's lazy day at home with Node.js

The context

Perfect Housewife will not rest after all day cleaning, even for a while. The saturday’s lazy evening is a time when she tries to lighten up home atmosphere. She used to bake some cake and serve it with coffee or tea as a good incentive to talk with members of her family. There is no better choice than warm yeast cake served with a bit of aromatic drink. There is no one in the family who would be dissapointed.

Shortly about Node.js

Node.js is a JavaScript runtime, designed to build scalable network projects. This highly customizable server engine allows applications to act as a web server (without IIS or Apache HTTP Server).

Simple node project with mysql

Prerequisities

  1. Coffee or tea
  2. Latest version of node.js engine installed on your machine - Node.js
  3. You need mysql server installed and running on default port
  4. Download tutorial project with database schema and sample data
  5. Be sure your system PATH contains path to node executable.
  6. You can use any text file editor but Perfect Housewife suggests you MS Visual Studio Code or atom.io.
  7. Create empty folder within your directory structure and name it node-tutorial
  8. Open up “Node.js command prompt”
  9. Open up text editor

Project folder structure

Project folder should contain at least one .js file used to start a project but it’s more common that the folder structure contains node_modules folder with project dependecies and also package.json with dependecies information for local install with npm.

node-tutorial/
|
|- node_modules/
|- package.json
|- file_name1.js
|- file_name2.js
|- ...

package.json

Create file package.json with content as follows:

{
	"name": "node-tutorial",
	"version": "0.0.1",
	"private": true,
	"dependencies": {
		"mysql": "*".
		"express": "*"
	}
}

This file is responsible for keeping name of the module (node-tutorial) and module dependencies which will be used by Node Package Manager npm. The dependecies are:

  • mysql is an mysql driver
  • express an mvc framework to create some routes (not neccessary but used here as an example)

Use npm to download module dependecies

Open up “Node.js command prompt” and run npm install from root of project directory. The NPM will download all the module dependecies described in package.json.

So now you’ve got a project folder with installed module dependecies - it’s a good practice for more complex projects.

http server

As a node.js engine doesn’t contain any type of server built-in you have to create this yourself. To do that you have to use http module from node.js itself:

var http = require('http');

with http we can reveive an res (response) and req (request) objects so now we have to take care of them:

function handleRequest(req, res) {
	res.end('It works! URL: ' + req.url);
}

the next thing to do is to create the server object:

var server = http.createServer(handleRequest);

and finally fire up the server so it can now listen for your requests:

server.listen(PORT, function(){
	console.log('Example app listening on PORT ' + PORT);
});

Open up the browsed and point the address to http://localhost:3000/test/url/for/example

! check file stage1.js from tutorial project package, you can run it from Node.js command prompt, just write: node stage1.js

## Creating and using mysql connection module

The common task is to read/write data from database, so we should create mysql object and set up the connection:

var mysql = require('mysql');
var connection = mysql.createConnection({
	host     : 'localhost',
	user     : '< db_user_name >',
	password : '< db_user_password >',
	database : 'node-tutorial'
});

connection.connect();

var sql = "SELECT * FROM users";
var message = "";
connection.query(sql, function(err, rows){

	if (err) {
		console.log(err);
		throw err;
	}

	for (var i = 0; i < rows.length; i++) {
		var row = rows[i];
		message += "User ID: " + row.id + "  User email: " + row.email + "  User name: " + row.name + "\n";
	}

});

connection.end(function(err){});

! check file stage2.js from tutorial project package, you can run it from Node.js command prompt, just write: node stage2.js

Create routing with simple output

In example we use Express framework for simple routing and serving. The framework gives you more enhanced experience than shown below. Read more about Express framework

var express = require('express');
var app = express();
var PORT = 3000;

...

app.get('/', function (req, res) {
	res.send('Hello World!');
});

app.get('/users', function(req, res) {
	res.send("<pre>Users list\n\n" + message + "</pre>");
});

var server = app.listen(PORT, function () {
	var host = server.address().address;
	var port = server.address().port;

	console.log('Example app listening at http://%s:%s', host, port);
});

! check file stage2.js from tutorial project package, you can run it from Node.js command prompt, just write: node stage2.js

Read more