The HTTP Server
The HTTP server generally serves the requested files or data. So there are some server side scripts that grab the requests and send the requested files/data. Here we will implement a simple HTTP server that serves files/data as the request.
Creating the HTTP Server
We will need some internal modules like http, fs (File System), url etc. Its easy to use these modules in anywhere in the node application. So in our code file we'll start by requiring the modules. Here we will use require() function to use modules. Then we will create server by createServer() method.
var http = require('http'), url = require(‘url’), fs = require('fs'); http.createServer ( function ( req, res ) { res.end("Hello world"); }).listen(8080, 'localhost'); console.log('Server running.');
This was the simple Hello World app we created first part. Simply if the client hits http://localhost:8080 and will get the "Hello World" message. We will extend this application and make it a client server application where client will make request to server and server will respond based on the request. Now client will hit with some parameters such as file name like index.html. So the request will look like http://localhost:8080/index.html. The request has two parts -- i) first one is the host part ‘http://localhost:8080’, and, ii) path-name ‘/index.html’.
var url_parts = url.parse(req.url); //testing what request found by url GET request console.log(url_parts); //pathName / means there is just host part in the requested url if(url_parts.pathname != '/') { // requested file serving fs.readFile( '.'+url_parts.pathname, function(err, data) { res.end(data);//just sending the read data from the file }); } else { // just respond with a confirmation message that the server is running when the request is http://localhost:8080 res.end("Hi, Server is running. This is Hello World. Thanks!"); }
So when the requested url has a pathname just like the 'hostName:port/pathName' the server will find out the file named as the
pathName. The file can be located in the inner directory or upper directory. If the file found, server will send response with the read file data otherwise server will send file not found message. When the request is just 'hostName:port' server will send response as “the server is running” as a confirmation message. But if the requested file is not found, it sends a file not found error message.
fs.readFile('.' + url_parts.pathname, function(err, data) { //if file not found error occured if(err) { res.end("<h1align='center' style='color:red'>I am sorry. File Not Found.</h1>"); } else { res.end(data); } });
The readFile() is an asynchronous function that takes the file name as first argument to read data and when reading is done the callback function is called. The callback has two parameters -- error and data. On success, the data event is occurred, otherwise the file not found event occurred.
Client side file index.html file is shown here
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/style.css" /> </head> <body> <div align="center"><h1>Hi This is index.html page.You are done.Good job.</h1></div> </body> </html>See the html has a CSS stylesheet file linked and the browser will request for the css file automatically. So when the client again requests for this file the same thing happens as the request for index.html file and after the css file is available on client side the css styles are applied to the index.html page and it is shown to the browser.
The css file look like this --
root { display: block; } div{ background: activeborder; margin: 100px auto; color:brown; }This functionality of a sever is called routing. For advance purpose we can use something like Flatiron module. For more info about Flatiron module please visit https://github.com/flatiron/flatiron site. We will see the flatiron tutorial next time.
So our final router should look like this
var http = require('http'), url = require('url'), fs = require('fs'); http.createServer(function (req, res) { // parse URL var url_parts = url.parse(req.url); console.log(url_parts+" query "+url_parts.query); if(url_parts.pathname != '/') { // file serving fs.readFile('.'+url_parts.pathname, function(err, data) { if(err) {res.end("<h1 align='center'>I am sorry. File Not Found.</h1>");} res.end(data); }); } else { res.end("Hi,Server is running.This is Hello World.Thanks"); } }).listen(8080, 'localhost'); console.log('Server running at localhost:8080');
The zip attachment contains the code file, html and css file.
Check out our other node.js content!
Attached Files
Edited by Roger, 19 February 2013 - 02:42 PM.
added links