-
Notifications
You must be signed in to change notification settings - Fork 12
/
loader.js
73 lines (68 loc) · 2.38 KB
/
loader.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
/* Nodeventure loader: loads room and item definitions and sets up a
* game object. It also handles reloading world modules as they change.
*
*/
var vm = require('vm'),
fs = require("fs"),
game = require('./game'),
cs = require('coffee-script'),
_ = require('underscore'),
WorldModule = require('./world').WorldModule;
module.exports.Loader = Loader;
function Loader(path) {
var _this = this;
this.game = new game.Game();
this.path = path;
this.modules = {};
this.update();
setInterval(_.bind(this.update, this), 5000);
// Game's emit has been extended to emit an 'all' event on any event
this.game.on('all', function (event /* ,args...*/) {
var args = _.toArray(arguments);
_.each(_this.modules, function (module) {
module.emit.apply(module, args);
});
});
}
_.extend(Loader.prototype, {
update: function () {
var files = fs.readdirSync(this.path),
_this = this;
for (var i = 0; i < files.length; i++) {
var file = files[i],
fullPath = this.path + "/" + file,
type = file.match(/^[^.~].*\.(js|coffee)$/);
// Check if it's a .js file.
// TODO: Add support for coffeescript, maybe for JSON also?
// Ignore files starting with ~ or .(it's an Emacs thing)
if (type && fs.statSync(fullPath).isFile()) {
var mtime = fs.statSync(fullPath).mtime + '';
// Check if the file has changed
if (!this.modules[file] || mtime !== this.modules[file].mtime) {
this.game.warn('Reloading world module:' + file);
// Ok, lets (re)load it!
var code = fs.readFileSync(fullPath, 'utf8'),
// Giving the module full access to node, could change
// this....
module = new WorldModule(this.game);
if(type[1] == 'coffee') {
try {
code = cs.compile(code);
} catch(e) {
this.game.error('FAILED TO COMPILE COFFEE SCRIPT: ' + e);
continue;
}
}
module.mtime = mtime;
try {
vm.runInNewContext(code, module, fullPath);
} catch (e) {
this.game.error("Loading world module: " + fullPath + "\n" + e.stack);
}
this.modules[file] = module;
}
}
}
return this;
}
});