Last Updated: February 25, 2016
·
514
· markuz-gj

promises and http module w/connect static server

simple factory function for creating a basic static server.


var http = require('http')
, Promise = Promise || require('es6-promise').Promise
, conn = require('connect')
;

function createServer (pub, port) {
  var app, server
  ;

  return new Promise(function(resolve, reject){
    app = conn()
      .use(conn.errorHandler({dumpExceptions: true, showStack: true}))
      .use(conn.static(pub))
      //.use(someAwesomeMiddleware())



    var server = http.createServer(app)
      .on('error', reject)
      .on('listening', function(){
        resolve(server)
      })
      .listen(port)
  })
}

module.exports = createServer

And use like so.


function errorHandler (err) {
 throw err
}

createServer('./public', 8181).then(function(server){
  // do stuff with server here.
  console.log('serving on port:', server.address().port)

}).catch(errorHandler)