-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
97 lines (77 loc) · 2.47 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
var sys = require("sys")
, fs = require("fs")
, http = require("http")
, repl = require("repl")
, ws = require('websocket-server')
, express = require('express');
var disabled_modules = ['fs'];
var PORT = 80;
function log(msg) {
sys.puts(msg);
}
/*-----------------------------------------------
Spin up our web server:
-----------------------------------------------*/
var app = express.createServer();
app.configure(function(){
app.use(express.methodOverride());
app.use(express.bodyDecoder());
app.use(app.router);
app.use(express.staticProvider(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
app.get('/', function(req, res){
res.sendfile('public/index.html');
});
/*-----------------------------------------------
Spin up our websocket server:
-----------------------------------------------*/
var server = ws.createServer({ debug: true, server: app });
server.addListener("listening", function(){
log("Listening for connections.");
});
var PROMPT = ">";
// Handle WebSocket Requests
server.addListener("connection", function(conn){
log("opened connection: "+conn.id);
conn.repl = repl.start(PROMPT, conn);
var req = conn.repl.context.require;
var bind = conn.repl.context.process.binding;
conn.repl.context.require = function(x) {
if (disabled_modules && disabled_modules.indexOf(x) > -1)
throw 'module access is disabled';
return req(x);
};
conn.repl.context.process.binding = function(x) {
if (disabled_modules && disabled_modules.indexOf(x) > -1)
throw 'module access is disabled';
return bind(x);
};
server.send(conn.id, "Connected as: "+conn.id);
conn.addListener("message", function(response){
var data = JSON.parse(response);
log("<"+conn.id+"> "+ data.action + " " + data.code);
if (data.action == "execute") {
var lines = data.code.split(/\n/);
for (var i=0; i<lines.length; i++) {
conn.repl.rli.write(lines[i]);
}
} else if (data.action == "complete") {
if (data.code) {
var result = conn.repl.complete(data.code);
if (result && result.length) {
conn.write(JSON.stringify(result));
}
}
}
});
});
server.addListener("close", function(conn){
log("closed connection: "+conn.id);
});
server.listen(parseInt(process.env.PORT) || 8000);