UNPKG

xserver

Version:
89 lines (74 loc) 2.13 kB
var mime = require("mime"); var getFile = require("./getfile"); function Directive ( request, response ) { this.request = request; this.response = response; this.sent = false; this.headers = {}; this.status = 200; this.url = {}; var pieces = request.url.split("?"); this.url.value = unescape(pieces[0]); this.url.segments = this.url.value.split(/\//g); }; Directive.prototype.setStatus = function( status ) { this.status = parseInt(status) || 500; }; Directive.prototype.setHeader = function( property, value ) { this.headers[property] = value; }; Directive.prototype.setContentType = function( value ) { this.setHeader("Content-Type", mime.lookup(value)); }; Directive.prototype.setData = function( data, encoding ) { this.data = data != undefined ? data : ""; this.encoding = encoding ? encoding : "utf8"; }; Directive.prototype.send = function () { this.response.writeHead(this.status, this.headers); if ( this.data && this.encoding ) { this.response.write(this.data, this.encoding); } this.response.end(); this.sent = true; }; Directive.prototype.sendStatus = function( status ) { this.setStatus(status); this.send(); }; Directive.prototype.sendText = function ( message, status ) { this.setContentType("txt"); this.setData(message); this.setStatus(status || 200); this.send(); }; Directive.prototype.sendObject = function ( obj, status ) { this.setContentType("json"); this.setData(JSON.stringify(obj)); this.setStatus(status || 200); this.send(); } Directive.prototype.prepareFile = function ( path, callback ) { getFile(path, (function ( err, data ) { status = 200; switch ( err ) { case "notfound": status = 404; break; case "notfile": status = 403; break; case "unreadablefile": status = 500; break; } this.setStatus(status); this.setContentType(path); this.setData(data, "binary"); callback(err); }).bind(this)); } Directive.prototype.getBodyObject = function ( ) { return this.body ? JSON.parse(this.body) : {}; }; module.exports = Directive;