-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathindex.js
85 lines (70 loc) · 1.92 KB
/
index.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
var fs = require('fs');
var log = require("./lib/util/log.js")("index")
// we just wrap the shared code
var telehash = global.telehash = module.exports = require('./lib/mesh.js');
// node specific extensions
module.exports.add(require('telehash-udp4'));
module.exports.add(require('telehash-http'));
module.exports.add(require('telehash-tcp4'));
//module.exports.add(require('telehash-webrtc'));
// attach our package+version to be helpful
module.exports.package = require('./package.json');
// wrap the mesh to accept file-based args
module.exports.load = function(args, cbMesh)
{
var idFile, linksFile;
// set up some node-specific things after the mesh is created
function loaded(err)
{
if(err)
{
log.error(err);
cbMesh(err);
return false;
}
return telehash.mesh(args, function(err, mesh){
if(!mesh) return cbMesh(err);
// sync links automatically to file whenever they change
if(linksFile) mesh.linked(function(json, str){
log.debug('syncing links json',linksFile,str.length);
fs.writeFileSync(linksFile, str);
});
cbMesh(err, mesh);
});
}
if(typeof args.links == 'string')
{
linksFile = args.links;
if(fs.existsSync(args.links))
{
log.debug('loading links',args.links);
args.links = require(args.links);
}
}
if(typeof args.id == 'string')
{
idFile = args.id;
if(fs.existsSync(args.id))
{
log.debug('loading id',args.id);
var err;
try{
args.id = JSON.parse(fs.readFileSync(args.id));
}catch(E){
err = E;
}
return loaded(err);
}
// create new
log.debug('generating new id');
telehash.generate(function(err,id){
if(err) return loaded(err);
args.id = id;
log.debug('saving to',idFile);
fs.writeFile(idFile, JSON.stringify(id, null, 4), loaded);
});
return;
}
// default passthrough
return loaded();
}