Using Node.js as a web server

Using Node.js as a web server

Introduction

Node.js is JavaScript that can be run outside of a browser. It is often used to make a fast server for dynamic content.

Probably one of the biggest advantages to Node.js, aside from being one of the fastest and easiest to learn server environments, is that JavaScript is the lanugage used on browsers, allowing you to program both the server and client in the same language.

Example

First, download and install node.js

Then, start the example by usign the command:

nodejs server.js

This example starts by sending a static HTML form when you visit http://localhost:8080/. It looks like the image below:

A screenshot of the main page, which is the static form.html file

Clicking the submit button on the form sends a get request to http://localhost:8080/submit. It looks like the image below.

A screenshot of the dynamically generated response to the form.

The interesting part of this script is the (url_parts.pathname == '/submit') condition. This is where the dynamic page generation happens. It starts by just regurgitating the information it was sent in the form. Note that the variable names of the url_parts.query.varname match up to the "name" attribute in each of the form elements. One of the most powerful features of node.js is that the program remains running between requests, unlike PHP. As a result, we can store variables which can retain their values as long as the process stays running. Storing any really important information this way is a bad idea, since a crash or shutdown would cause the data to disappear. A database can be used, such as MySQL. However, probably the most popular database for node.js servers is MongoDB, which uses JSON encoded data.

This form would also work by POST, if the form method were changed from GET to POST.

var http = require('http'); // these lines are somewhat similar to #include in C++
var util = require('util'); // except that the left hand side is an object/variable
var url = require('url');
var fs = require('fs');

// provide a "database"
messages = []

var server = http.createServer(function (req,res){
	 // parse the URL
	var url_parts = url.parse(req.url,true);

	// functions to serve static files
	function sendHTML(filepath) {
		// read the file asyncronously
		fs.readFile(filepath,function(error,contents){ 
			// once the file is loaded, this function runs
	    	console.log('Serving the html ' + filepath);
	    	res.end(contents); // end the request and send the file
	    });
	}
	function sendCSS(filepath) {
		// once the file is loaded, this function runs
		fs.readFile(filepath,function(error,contents){ 
	    	console.log('Serving the css ' + filepath);
	    	res.end(contents); // end the request and send the file
	    });
	}

	// serve the index page from a static file
	if( url_parts.pathname == '/' ) {
		sendHTML('./form.html');
	}
	// serve the CSS page from a static file
	else if ( url_parts.pathname == '/style.css') {
		sendCSS('./style.css')
	}
	// generate a dynamic page
	else if ( url_parts.pathname == '/submit' ) {
		var html = '<html><body>'; // begin the minimal html structure
		html += "<h2>Query received</h2>";
		html += "Name: " + url_parts.query.name;
		html += '<br />';
		html += "Email: " + url_parts.query.email;
		html += '<br />';
		html += "Message: " + url_parts.query.message;
		html += '<br />';

		html += '<h2>Previous Messages</h2>';
		messages.push(url_parts.query.message)

		// loop through the old messages
		for(m in messages) {
			html += messages[m];
			html += '<br />';
		}

		html += '</body></html>'; // end the minimal html structure

		res.end(html); // end the request and send the response HTML
	}
	// if the url was not recognized, 404
	else {
		res.writeHead(404) // put a header for not found
// print the page and end the request res.end("<h1>404 - Path not recognized</h1>"); } }); server.listen(8080); util.log('Server listenning at localhost:8080');
Evan Boldt Mon, 08/04/2014 - 18:59
Attachments