UNPKG

wns-static-package

Version:

Static file server package/bundle for WNS HTTP Package

168 lines (148 loc) 3.32 kB
/** * WNS's HTTP Package * @copyright &copy; 2013- Pedro Nasser &reg; * @license: MIT * @page http://github.com/pedronasser/wns-http-package */ /** * @class wnStaticServer * @classdesc Intercepts incoming request of wnHttp server and handles static file requests. * @author Pedro Nasser */ module.exports = { /** * Class dependencies */ extend: ['wnComponent'], /** * NPM Dependencies */ dependencies: ['node-static'], /** * Private */ private: { _server: null, _config: { serve: ['public/'], options: { cache: 3600, headers: {}, serverInfo: "WNS Static Server", gzip: false } } }, /** * Public Variables */ public: { /** * @var object events to be preloaded. */ defaultEvents: { 'open': {}, 'error': {}, 'send': {} } }, /** * Methods */ methods: { /** * Initializer */ init: function () { this.module = this.getParent(); this.prepareServers(); this.attachEvents(this.module); }, /** * Prepare StaticServer to serve all directories; */ prepareServers: function () { this.server = []; var dirList = this.getConfig('serve') || []; for (d in dirList) { if (fs.existsSync(this.module.modulePath+dirList[d])) { self.debug('Serving static files on: '+dirList[d],1); this.server.push(new node_static.Server(this.module.modulePath+dirList[d],this.getConfig('options'))); } } }, /** * Attach events to the application * @param {wnApp} module */ attachEvents: function (module) { self.debug('Attaching events to the parent application',0); if (!_(module).isObject()) return false; module.addListener('newRequest',self.processRequest); }, /** * Process the request * @param object $req client request instance */ processRequest: function (e,req,resp) { self.debug('Try process `'+req.url+'` as static file',1); var s = 0; (function () { if (s >= self.server.length) { e.next(); } else { var args = arguments; self.debug('Using server #'+s+' ['+req.url+']',2); self.server[s].serve(req,resp,function (err) { if (err !== null) { s++; args.callee(); } }); } })(); }, /** * Promise: Serve a file from the serving directory. * @param wnHttpRequest $req request instance * @param string $filename filename * @param number $modified compare file modification (optional) */ $serve: function (req,resp,filename,modified) { var filePath = self.module.modulePath+this.getConfig('serve')[0]+filename; modified = modified || 0; if (!_.isString(filename), !_.isNumber(modified)) done.resolve(false); else { fs.stat(filePath,function (err,stats) { if (err) done.resolve(false); else { var mtime = +new Date(stats.mtime) if (modified <= mtime) { self.debug('Serving modified file.',1); self.server[0].serveFile(filename,200,{},req,resp); done.resolve(true) } else done.resolve(false); } }) } return done.promise; } } };