User:Tsu2/nodejs webserver

Jump to: navigation, search

Nodejs Webserver

If you need to install nodejs
Installing nodejs on openSUSE

I don't think that nodejs is generally recommended as a Production webserver, but there are many times you might want to quickly invoke a simple webserver to view some documentation or develop website code. You don't want or need the heavy, complex and over-siezed Apache for just yourself or only a few others. Nodejs to the rescue!

Although the nodejs website usually displays a simple website configuration file, you may need to configure your website more fully. The following is currently my preferred. If anyone has another favorite configuration, contributions are welcome!

Perfect for developing static websites, the website will refresh automatically whenever file changes are detected.

# node.js webserver script
# This is not required for the project but useful if you opt to use node as your webserver
# Instructions
# Install node.js
# Create a file "webserver.js" with this content
# Create a file "index.html" with your homepage content
# From a command line in the same directory "run node webserver.js"

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs")
    port = process.argv[2] || 80;

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");