Thinking & Doing


Feed
BY  Stephen Gilboy  ON  11-25-2013 11:07 AM

What is NodeJS?

NodeJS is a platform built on top of Google's V8 engine that is used to build network applications. Using the modules and JavaScript you can create lots of fun stuff for example a web server or a TCP server. Node is event based so you will write asynchronous code to build your application. It is also single threaded which means if you block the thread you block the whole application so you'll only want to use Node for I/O and not CPU heavy applications.

Why use Node?

It is free as in "free beer"! Node is very good at handling a lot of requests. In fact Groupon has recently replaced their Ruby on Rails servers with NodeJS. They are now handling 50,000 requests per minute with less hardware. Also, it is JavaScript so now the frontend developers can help out on server side coding.

Who is using it?

NodeJS is no longer a hipster technology only used by startups. It has a lot of big name companies using it like Groupon, LinkedIn, eBay, The New York Times. Even Wal-Mart uses NodeJS for their mobile applications.

Alright Let's Code!

First go to the NodeJS website and install node, I'll wait.

Installed? Good.

Now lets create a simple web server so fire up your favorite text editor and lets write some JavaScript.

var http = require('http');
var server = http.createServer(function(req, res) {
    res.writeHead(200, { 'content-type' : 'text/plain' });
    res.write('Hello,');
    res.end('World.');
});
server.listen(3000);

The first line of this code you are requiring Node's HTTP module. If you were creating a TCP server you would require 'net'. Next we're creating the server and sending in an anonymous function that creates the response to send to the client. Then tell the server to listen on port 3000.

Now just save that as web.js, or whatever you want to call it, and then open up a terminal, or command prompt, and navigate to the file and write 'node web.js'. If the terminal shows no errors fire up your browser and navigate to localhost:3000.

Fun huh?

ExpressJS

I know what you're thinking and we'll be using the ExpressJS framework to clean up all the request/response stuff. So now we'll create a new file in the same directory as your web.js file and call it 'package.json'. Add the following to package.json

{
 "name": "MyCoolWebApp",
 "version": "0.0.1",
 "private": true,
 "scripts": {
   "start": "node web.js"
 },
"dependencies": {
  "express": "3.4.4"
 }
}

Once you've saved that go back into your terminal and run the following: 'npm install'. npm is Node's package manager and it'll go out and get us the Express framework. Now lets go back into web.js and write some new code.

var express = require('express');
var app = express();
app.get('/', function(req, res) {
    res.send('Hello, World!');
});
app.listen(3000);

Much nicer. Now instead of specifying the header and all the response write/end stuff we just use the send() method. Express makes handling routes a lot better. The first argument of app.get() is the route.

NOTE: You will need to restart the server after you add code. So if it is running just hit ctrl+c to end it and the 'node web.js' to start it up again.

Lets add a new route:

var express = require('express');
var app = express();
app.get('/', function(req, res) {
    res.send('Hello, World!');
});
app.get('/user', function(req, res) {
    res.send('User page');
});
app.listen(3000);

Cool. Now lets have some MVC route goodness and have our user profile at /user/(username). Add the following:

app.get('/user/:name', function(req, res) {
    if(req.params.name) {
        res.send('Hello ' + req.params.name);
    } else {
        res.send('User Page');
    }
});

Adding :name to our route means we can access whatever is passed there in the req.params object. Now when you navigate to say localhost:3000/user/Gilboy you should see 'Hello Gilboy'.

If we want to use query parameters we can easliy do that. Let's modify the '/user/' route.

app.get('/user', function(req, res) {
    if(req.query.name) {
        res.send('Hello ' + req.query.name);
    } else {
        res.send('User page');
    }
});

Now navigate to localhost:3000/user/?name=Stephen%20Gilboy and you should see 'Hello Stephen Gilboy'.

Wrap It Up

As you can see you can get a web app up and running quickly without having to install Apache or IIS. ExpressJS also has a lot more to it than what we've covered so I highly suggest reading through their documentation. There are a lot more packages for Node which you can find at the NPM Website. Socket.IO is a fun one that you use to create real-time web apps. Draw on a canvas with friends or make a full HTML5/JS game with it.

Hopefully you now have a better understanding of what Node is and why you would want to use it. In future posts I will go more in depth of some of the packages.

Thanks for reading now go make something.

SYNDICATION