Simple HTTP server using Node

Posted on 7/27/2015 @ 4:58 PM in #Vanilla .NET by | Feedback | 1902 views

Sometimes you need a simple http server to serve simple static files – say if you’re writing cordova apps, and don’t want to package every single time before debugging.
You could run a simple http server using python, as I tweeted earlier,

But, what if you don’t have python installed, or if you wish to include starting an http server as a gulp task in your favorite IDE (say Visual Studio code)?

Simple! Here is how you create the gulp task to run the http server using node.js -

   1:  gulp.task('build', function () {
   2:      var http = require("http"),
   3:          url = require("url"),
   4:          path = require("path"),
   5:          fs = require("fs"),
   6:          port = 8888;
   7:   
   8:      http.createServer(function (request, response) {
   9:          var uri = url.parse(request.url).pathname
  10:              , filename = path.join(process.cwd(), uri);
  11:   
  12:          fs.exists(filename, function (exists) {
  13:              if (!exists) {
  14:                  response.writeHead(404, { "Content-Type": "text/plain" });
  15:                  response.write("404 Not Found\n");
  16:                  response.end();
  17:                  return;
  18:              }
  19:   
  20:              if (fs.statSync(filename).isDirectory()) filename += '/index.html';
  21:   
  22:              fs.readFile(filename, "binary", function (err, file) {
  23:                  if (err) {
  24:                      response.writeHead(500, { "Content-Type": "text/plain" });
  25:                      response.write(err + "\n");
  26:                      response.end();
  27:                      return;
  28:                  }
  29:                  response.writeHead(200);
  30:                  response.write(file, "binary");
  31:                  response.end();
  32:              });
  33:          });
  34:      }).listen(parseInt(port, 10));
  35:   
  36:      console.log("Static file server running at\n  => http://localhost:" + port);        
  37:  });

 

Hope someone finds this useful!

Sound off but keep it civil:

Older comments..