How to create a static server using nodejs

Folks,

Good Noon..

Good things happens with good sharing of knowledge..

I gain something good knowledge from this great techie geeky Ryan Florence today.

Actually my scenario looks like this..

I have to build a project say project zero..where it have to run on its own without any wamp/IIS servers. Project should run with its own server using nodejs. So i have a filename called app.js where that single js file acts like a server to run my index.html page in http://localhost:8888

What i have to do for all this is only two steps:

1. run the command in command prompt (myprojectpath>node app.js)

2. hit the url in my funky browser. (http://localhost:8888)

Lets go through the code now..

app.js:

var http = require(“http”),
url = require(“url”),
path = require(“path”),
fs = require(“fs”)
port = process.argv[2] || 8888;

http.createServer(function(request, response) {

var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);

path.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {“Content-Type”: “text/plain”});
response.write(“404 Not Found\n”);
response.end();
return;
}

if (fs.statSync(filename).isDirectory()) filename += ‘/index.html’;

fs.readFile(filename, “binary”, function(err, file) {
if(err) {
response.writeHead(500, {“Content-Type”: “text/plain”});
response.write(err + “\n”);
response.end();
return;
}

response.writeHead(200);
response.write(file, “binary”);
response.end();
});
});
}).listen(parseInt(port, 10));

console.log(“Static file server running at\n => http://localhost:” + port + “/\nCTRL + C to shutdown”);

index.html:

This is index.html

Steps to follow to run and check:

1. Open command prompt and do as follows

14-12-2014 13-30-01

2. Just type http:localhost:8888

14-12-2014 13-32-30

Thats it..soo crazy code right 😉

Just say thanks to https://gist.github.com/rpflorence 🙂

Source: https://gist.github.com/rpflorence/701407

 

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