Beginner’s Guide to Node.js (Server-side JavaScript)

Beginner’s Guide to Node.js (Server-side JavaScript).

Creating a HTTP Server

Now it’s time to create a “Hello World” via web server using Node.js. Here’s what we are going to do – we create a server that outputs a “Hello World” to the localhost on the port 8080 no matter what the URL is, giving you an idea what event is.

The codes:

  1. var sys = require(“sys”),  
  2. my_http = require(“http”);  
  3. my_http.createServer(function(request,response){  
  4.     sys.puts(“I got kicked”);  
  5.     response.writeHeader(200, {“Content-Type”“text/plain”});  
  6.     response.write(“Hello World”);  
  7.     response.end();  
  8. }).listen(8080);  
  9. sys.puts(“Server Running on 8080”);  

Creating simple static file server

Let’s create a simple static file server in the next tutorial.

The codes:

  1. var sys = require(“sys”),  
  2. my_http = require(“http”),  
  3. path = require(“path”),  
  4. url = require(“url”),  
  5. filesys = require(“fs”);  
  6. my_http.createServer(function(request,response){  
  7.     var my_path = url.parse(request.url).pathname;  
  8.     var full_path = path.join(process.cwd(),my_path);  
  9.     path.exists(full_path,function(exists){  
  10.         if(!exists){  
  11.             response.writeHeader(404, {“Content-Type”“text/plain”});  
  12.             response.write(“404 Not Found\n”);  
  13.             response.end();  
  14.         }  
  15.         else{  
  16.             filesys.readFile(full_path, “binary”function(err, file) {  
  17.                  if(err) {  
  18.                      response.writeHeader(500, {“Content-Type”“text/plain”});  
  19.                      response.write(err + “\n”);  
  20.                      response.end();    
  21.   
  22.                  }  
  23.                  else{  
  24.                     response.writeHeader(200);  
  25.                     response.write(file, “binary”);  
  26.                     response.end();  
  27.                 }  
  28.   
  29.             });  
  30.         }  
  31.     });  
  32. }).listen(8080);  
  33. sys.puts(“Server Running on 8080”);  

Codes explanation:

This entry was posted in nodejs. Bookmark the permalink.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s