Tuesday, April 9, 2013

Creating a simple webserver with node.js and Expressjs

Foreword

I played with angularjs for a while and struggled a little as I didn't find an easy way to simulate json responses. I want to decouple the client completely from the server so that it is possible to work in my nifty little javascript world without having to take care about the server part that is running on Spring/Java. I'm mainly doing that because I want to decouple as much code as possible to outsource parts to other developers that are experts in their segment. I don't want that a javascript developer needs knowledge about Java or any other development language. I also want to split projects in to chunks, spread them among different developers and set them together to the full picture once complete.
At last I found my solution with node.js and the Expressjs server. This is an easy example to setup a "one-script" solution to simulate json responses. This article is not intended to teach others but to share knowledge and learn.

Installation

Install node.js by downloading the corresponding binary package. I have downloaded the Linux binary package. I like to keep binaries like this in my home directory. So I did the following:
mkdir $HOME/Programs
cd $HOME/Downloads
tar -xvzf node-v0.10.3-linux-x64.tar.gz
mv node-v0.10.3-linux-x64 $HOME/Programs
Then I added the bin directory to the path so that the commands can be executed.
vim $HOME/.bashrc
export PATH=$PATH:$HOME/Programs/node-v0.10.3-linux-x64/bin
After opening a new terminal window I tested if node.js has been added to the path correctly:
node -v
v0.10.3

Creating the webserver

I have created a folder to install the webserver.
mkdir $HOME/Documents/node-server-example
Then I changed in to the directory and created a file called package.js.
cd $HOME/Documents/node-server-example/
vim package.json
{
  "name": "Express Test Server",
  "description": "Testing the Express Server",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "3.x"
  }
}
After that I have executed following command to install the Express Webserver.
npm install
This created a directory called node_modules with the express server dependencies in it. Then I have created a file called server.js that contains the server dependent code.
vim server.js
var express = require('express');

var app = express();

app.get('/api/user/email/testemail1', function(req, res) {
  res.status(201);
  res.json({ message: "this sends status header 201 (Created)" });
});
app.get('/api/user/email/testemail2', function(req, res) {
  res.status(200);
  res.json({ message: "this sends status header 200 (OK)" });
});

app.listen(3000);
console.log('Listening on port 3000...');
Then I started the webserver and browsed to the site with the Firefox RESTClient.
node server
Listening on port 3000...
And voila..... that was it. Pretty amazing.

Additional Sources

1 comment: