-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (55 loc) · 1.69 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
#!/usr/bin/env node
var fs = require('fs'),
Firebase = require('firebase'),
argv = require('minimist')(process.argv.slice(2)),
colors = require('colors');
if (!argv.firebase) console.warn("Please specify a Firebase with --firebase");
if (!argv.path) {
console.log('Assuming path /'.blue);
argv.path = '/';
}
if (!argv.file) {
argv.file = 'fire.json';
console.log(('Assuming file ' + argv.file).blue);
}
if (argv.path[0] !== '/') argv.path = '/' + argv.path;
console.log('Firebase:', argv.firebase.green);
console.log('Path:', argv.path.green);
var rootRef = new Firebase(argv.firebase + '.firebaseio.com'),
ref = rootRef.child(argv.path),
last, readyToClose;
fs.writeFile(argv.file, "", function (err) {
ref.on('value', function (snap) {
last = snap.val();
fs.writeFile(argv.file, JSON.stringify(snap.val(), null, 2), function (err) {
if (err) throw err;
});
});
fs.watchFile(argv.file, function (curr, prev) {
fs.readFile(argv.file, function (err, data) {
var data;
if (err) {
console.log('File deleted!')
return process.exit(0);
}
try {
data = JSON.parse(data.toString());
} catch (e) {
console.log(e.toString().red);
return;
}
if (last == data) return;
ref.set(data);
console.log('Updating Firebase', new Date());
});
});
process.on('exit', exitHandler.bind(null,{cleanup:true}));
process.on('SIGINT', exitHandler.bind(null, {exit:true}));
});
function exitHandler(options, err) {
if (!readyToClose)
fs.unlinkSync(argv.file);
readyToClose = true;
if (options.cleanup) console.log('Cleaning up...'.blue);
if (options.exit) process.exit();
}