Using node.js to serve static html web pages

If you are a beginer for node here is the definition as per nodejs.org

It’s a platform built on chrome’s javascript runtime for easily building fast scalable network applications. Node.js uses and event driven, non-blocking IO model that makes it lightweight and efficient, perfect for data intensive real-time applications that run on distributed devices. 

I started with node hello-world app and quickly started comparing with the traditional web frameworks. Realised that to take advantage of node it should serve the basic needs of the typical internet application platform only then we can scale it to build advanced, seamless, complex and robust web applications. Hence I defined a first task to myself:  “Creating a WebServer serving static html web pages“.

Here is the brief tutorial to how to get that going: Install node from nodejs.org.

create package.json and add the following lines:

{
“name”: “static-web”
, “version”: “0.0.1”
, “private”: true
, “dependencies”: {
“requirejs”: “latest”
, “connect”: “2.7.0”
}
, “devDependencies”: {
“path”: “latest”
, “events”: “latest”
}
, “scripts”: {

}
}

run npm install on command prompt to install dependent packages. The server is created using http.createServer command and need to use the filesystem module and pass html files to the server requests. 

The code looks like:

http.createServer(function(request, response) {

var lookup = path.basename(decodeURI(request.url)) || ‘index.html’,f=’content/’ + lookup

}).listen(8000);

Once the server is configured run the following command to fire up the server

node server.js

you are done! server is up and running subsequently we can add many html files in this folders with links etc.. to server a static web server. Download complete code from github using the following command:

git clone https://github.com/uhbl92/node-static-server.git

 

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