/
autoreload.js
69 lines (62 loc) · 2.03 KB
/
autoreload.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
//
// node.js auto reload module
// by Shimon Doodkin.
// license: 2 close BSD.
//
var path = require('path');
var fs = require('fs');
var loadmoduletimer={};
var trackedfiles={}; exports.trackedfiles=trackedfiles;
// note: there is an upcomming version of node
// with auto reload modules probably it will be integrated in the near future.
//
// also every time you reload a module it does not free the memory of the reviews module.
// it means that reloading modules sutes fine for development,
// but do not relay on havy use of it for production.
function loadlater( filename , callback )
{
console.log((new Date).toString()+' will load file: '+filename);
return setTimeout(function ()
{
console.log((new Date).toString()+' loading file: '+filename);
fs.readFile(filename, function (err, content)
{
if (err) throw err; // need to add better error handling
try
{
var dirname = path.dirname(filename);
// create wrapper function
var wrapper = "(function (exports, require, module, __filename, __dirname) { "
+ content
+ "\n});";
var compiledWrapper = process.compile(wrapper, filename);
var newmodule={};
compiledWrapper.apply(newmodule, [newmodule, require, newmodule, filename, dirname]);
callback(newmodule);
}
catch(err)
{
if (err) throw err; // need to add better error handling
}
});
}, 500); // sometimes i had a situation when the watchFile callback called while uploading the file and resulted in error.
}
function watch(filename,callback)
{
trackedfiles[filename]=true;
fs.watchFile(filename, function ()
{
if(loadmoduletimer[filename])
{
console.log((new Date).toString()+'timeout cleaned - will load file: '+filename);
clearTimeout(loadmoduletimer[filename]);
}
loadmoduletimer[filename] =
loadlater( filename ,callback);
});
};exports.watch=watch;
function watchrel(filename,callback)
{
watch(__dirname+'/'+filename,callback);
};
exports.watchrel=watchrel;