bute
Version:
The complete distribution solution for NodeJS
75 lines (61 loc) • 2.29 kB
JavaScript
var eventEmmiter = require("events").EventEmitter;
var util = require("util");
var fs = require('fs');
var path = require("path");
var protoBuf = require("protobufjs");
var debug = require('debug');
var fsDebug = debug("FileSystem");
var WARDEN = require('./lib/warden');
var SERVER = require('./lib/comm_init').server;
var SOCKET = require('./lib/comm_init').socket;
// Protocol Buffers
var builder = protoBuf.loadProtoFile(path.join(__dirname, "protocol", "init.proto"));
var Introduction = builder.build("Introduction");
var bute = new Object;
bute.connections = new Array();
bute.sockets = new Array();
fs.readFile('./butefile.json', 'utf8', function (err, data) {
if (err) {
if(err.code === "ENOENT") fsDebug("butefile.json not found! Create one manually or using `bute` command-line");
else console.log(err);
bute.config = new Object;
}else bute.config = JSON.parse(data);
});
bute.server = function (port) {
eventEmmiter.call(this);
var _this = this;
this.server = new SERVER(port || 8100);
this.server.on('join', function(address, connection) {
var allowed = false;
if(WARDEN.check(address, bute.config.allow).length) allowed = true;
var intro = new Introduction({ identity: "HOST", allowed: allowed });
connection.write(intro.encode().toBuffer());
if(allowed) {
bute.connections[address] = { connection: connection, debug: debug("slave:" + address)};
_this.emit('joined', address, connection);
bute.connections[address].debug('connected');
connection.on('end', function() {
bute.connections[address].debug('disconnected');
bute.connections[address] = undefined;
})
}else{
connection.end();
}
})
return this;
}
bute.socket = function (port) {
eventEmmiter.call(this);
var _this = this;
this.socket = new SOCKET(port || 8100);
this.socket.on('data', function(data){
_this.emit('data', Introduction.decode(data));
});
return this;
}
util.inherits(bute.server, eventEmmiter);
util.inherits(bute.socket, eventEmmiter);
module.exports = {
server: bute.server,
socket: bute.socket
};