Wednesday, September 25, 2013

NodeJS Web Server for local testing

For my 'day to day' work I usually need to spawn number of web servers to serve files form different locations. Of course those servers need to listen on dedicated ports. The easiest, by far quickest and really simple way to do this is by utilizing NodeJS:
  • Install NodeJS by opening http://nodejs.org/ and clicking Install button
  • Install Required modules by typing in the console: npm install stdio connect
  • Copy modules to home folder: mv node_modules ~/.node_modules
  • Create webserver.js:
    var stdio = require('stdio');
    var connect = require('connect');
    
    var ops = stdio.getopt({
        'dirname': {key: "dir", args: 1, description: 'Web Server Folder'},
        'webport': {key: "port", args: 1, description: 'Web Server Port'}
    });
    
    if (ops.help) {
        ops.printHelp();
    }
    
    if (!ops.dirname) {
      ops.dirname = __dirname;
    }
    
    if (!ops.webport) {
      ops.webport = 8080;
    }
    
    console.log("Web Server is listening on port " + ops.webport + " and serving: " + ops.dirname)
    
    connect.createServer(                                                                                      
        connect.static(ops.dirname)                                                                            
    ).listen(ops.webport); 
    
  • Create webserver executable:
    #!/bin/bash
    
    BASEDIR=$(dirname $0)
    APPDIR=`pwd`
    
    node $BASEDIR/webserver.js $@ --dirname $APPDIR
    
  • Paste webserver and webserver.js into your bin folder (added to your $PATH)
  • Start webserver as following:
    
    #from any folder where you have index.html
    webserver
    
    #or if you want to specify port
    webserver -port 8081
    
    #you will see something like
    Web Server is listening on port 8081 and serving: /Users/rkuzmik/Work/DeftJS/IoC-Q-app
    
    
Enjoy!