m_jet
Version:
full stack node framework
98 lines (82 loc) • 2.38 kB
JavaScript
// m_jet server
//
var dataplex = require('dataplex')
var routes = require('routes')
var shoe = require('shoe')
var http = require('http')
var url = require('url')
var fs = require('fs')
var debug = false
function _jet (options) {
if ( !(this instanceof _jet) ) {
return new _jet(options);
}
this.public_dir = process.cwd() + '/public';
this.ecstatic = require('ecstatic')(this.public_dir)
this.plex = new dataplex()
this.router = routes()
var self = this
this.server = http.createServer(function(req, res) {
var path = url.parse(req.url).pathname
var match = self.router.match(path)
if (req.method === 'OPTIONS') {
res.statusCode = 200
res.end()
}
if (match) {
match.fn(req, res, match)
} else {
self.ecstatic(req, res)
};
});
this.defaultHeader = function (stream) {
stream.setHeader('Content-Type', 'text/html')
};
this.read_file = function (file) {
var file_path = self.public_dir+'/'+file;
return fs.createReadStream(file_path, 'utf-8')
};
this.json = function (stream, data) {
stream.setHeader('Content-Type', 'application/json')
stream.write(JSON.stringify(data))
stream.end()
};
this.render = function render(stream, file) {
this.read_file(file).pipe(stream)
};
this.render_html = function render(stream, file) {
this.defaultHeader(stream)
this.render(stream, file)
}
this.sock = shoe(function (stream) {
stream.pipe(self.plex).pipe(stream);
stream.on('error', function (err) {
console.log(err)
});
});
this.socket = function (callback) {
callback(self.plex)
};
this.sock.on('error', function (err) {
console.log(err)
});
this.sock.on('connection', function(conn) {
if (debug) console.log('connection: ', conn)
conn.on('close', function() {
if (debug) console.log('socked closed: ', conn)
});
conn.on('data', function(message) {
if (debug) console.log('message: ' + conn, ' ', message)
});
});
if (debug) this.sock.on('log', function (data) { console.log('[log] ', data) })
this.start = function (_port, _label) {
var port = _port;
var label = (_label) ? _label : '[m_jet]';
if (!port) port = 4008;
self.sock.install(self.server, '/m_jet');
self.server.listen(port);
console.log(label + ' listening on port ' + port)
};
}
module.exports = _jet;