Node.js 101: #2 The Basic of Node.js

Yesterday, I wrote my first post about Node.js explaining how to deal with its asynchronous non-blocking nature. Now in this post, let jump inside and learn how to code in Node.js. I won’t explain to you about the basic coding (such as sequence, branching and looping) because it is just as same as Javascript language that you know before.

What sort of thing do Node.js has but Javascript hasn’t?

Javascript runs inside your browser and deal with its action inside of it, so there will be a function to display alert, change animation, fadeIn, fadeOut, and something like that. That kind of capability aren’t included in Node.js obviously because Node.js acts like console/terminal program that get or print the stream from/into STDIN/STDOUT.

I never say that Node.js has no capability to deal with DOM manipulation in HTML. It has however but not in context of live browser view (this is just as same as other programming language which has web scraping library to deal with DOM manipulation).

Installing Node.js into my system

You can find Node.js binary package for Windows, and Mac OS X in its website.

How about Linux user? Well, you can install node package via Package Manager provided by your distribution. Debian and its derivative can do this magic mantra : apt-get install node. But unfortunately, most of Debian distribution came with old version of Node (0.6.x) which is very incompatible with most of Node.js Library. You can do manual compiling from source code (It is provided in as same link as Node.js binary package) or use custom user based repository (like PPA/GetDeb/Medibuntu).

Our first code

To say hello world in Node.js via console/terminal, you just write a file like this.

console.log("Hello world")

Save it as hello.js, then run it via this command : node hello.js. Yes, this sort of code is actually can be used in casual browser Javascript (and it will printed out inside the Development Console). This is demonstrating one thing that Node.js has plus point: You can share a single codebase between your server and web client application in some cases.

Basic #1: Creating a echo server TCP socket

This basic is rather simple. This code is just copy-pasted from Node.js main website.

var net = require('net');

var server = net.createServer(function (socket) {
  socket.write('Echo server\r\n');
  socket.pipe(socket);
});

server.listen(1337, '127.0.0.1');

This code is very simple actually. The first line is to import a library called “net” (which provided capability of socket server). This library is imported into variable called net (Yes, you have to use var keyword every variable declaration although you don’t have to tell its data type). The second (not counting blank line) line is calling a function called createServer function its (non-optional) argument only asking a callback. The structure of its callback (required from the API) have to including single argument which will passed by some object. This passed object will be used inside of createServer callback function to do something. In that example, the socket object is used to write an output of 'Echo server\r\n' and then pipe its stream (You can see what this object has from this API documentation). This callback is called when a host create a TCP connection, and this whole line won’t block the next line (That is basic principle for Node.js).

The last line is to do TCP socket listening in port 1337 and IP 127.0.0.1 (of course you can use 0.0.0.0 or a multicast IP to make it listened by some host).

Basic #2: A simple web server

Yes, you can use “net” library to do that. But are you kidding me? Node.js provide a special library for special case of TCP Web Server so you don’t need to verbosing your code. Here is a sample code taken from Node.js website :

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

The first line is obviously a mechanism to import library called http. The second line is the process of calling createServer method which its mandatory argument is callback with two argument, req and res which actually a JS object for request and response. Inside the callback function body, the response is used for writing a 200 HTTP response (OK) which ended with a data which is 'Hello World\n' string.

Rather than creating a special variable for createServer call (like in previous sample), this sample just call listen method by chaining it after createServer call. You can do that kind of chaining just like in usual Javascript or maybe in another programming language (except PHP :P).

Introducing to npm

Node.js actually has some build in library to get started with web or socket programming. It is documented very well in API documentation.

To extend its capability, Node.js has a lot of community created library which will add its functionality and make coding became easier. All the library is provided by single centralised package manager called npm. You can install or remove a library globally or only on your project.

To install a package, it just like doing pip in Python or gem in Ruby like this :

npm install package-name # Install locally in current folder
npm -g install package-name # Install globally

NPM provide a website called npmjs so you can browse many library you wanted via web browser.

Basic #3: Do a database reading

I will give you an example about how to use Node.js to access database server. For demonstration purpose, I will use MySQL server and “nodejsdb” library (go install it through npm). This is an example code copy-pasted from nodejsdb main website :

var mysql = require("db-mysql");
new mysql.Database({
    "hostname": "localhost",
    "user": "user",
    "password": "password",
    "database": "test"
}).connect(function(error) {
    if (error) {
        return console.log("CONNECTION error: " + error);
    }
    this.query()
        .select(["id", "user", "email"])
        .from("users")
        .where("role IN ?", [ ["administrator", "user"] ])
        .and("created > ?", [ new Date(2011, 1, 1) ])
        .execute(function(error, rows, columns){
            if (error) {
                console.log('ERROR: ' + error);
                return;
            }
            // Do something with rows & columns
        });
});

Again, this code is actually very simple if you understand the concept of asynchronous and non-blocking programming in my previous post. This code has only three function call with a callback and a callback inside of callback (heavy breathing).

The first line is obviously library importing function. The second one is a very long line which created in separated line just to make easier to read. It created a mysql.Database object which its only argument is some field needed to connect to a database server.

Then this function is chained with .connect function so you don’t need to hold that previous object inside a defined variable. This function needs one callback with one argument called error which literally will hold some error message if there is (Yes, it will be printed and returned if there is). Then if no error happens, it call a function called this.query (this keyword refer to previous mysql.Database). This function require no argument and actually creating a query object (same like cursor object in Python). This new object chained with many function and the last chaining function is execute which in turn to execute a query object which previously defined. execute require a callback which will be called when the querying process is done. And you can access the data from row and columns variable inside the callback.

The lesson so far

If you still confused with this callback thing, here is some sort tips for you : In Node.js, every function that require some waiting process (like IO or TCP/Web request) act asynchronously. So this need a callback, which will be called when the process of IO call is done. In conventional programming, if you deal with this kind of situation, the program trace may be breaked for a while to wait and it could blocked the entire program if you don’t used special mechanism like thread. Imagine how often will this process required in networked or distributed system. When it comes to Node.js, the programmer would be much happier because they don’t need to manually code the mechanism of synchronisation, thread, and deadlock (something I learned in first week of Operating System class) manually.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *