-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelite-journal.js
100 lines (69 loc) · 2.35 KB
/
elite-journal.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
97
98
99
100
// Node.js libraries
const EventEmitter = require('node:events');
const path = require('path');
const os = require('os');
const fs = require('fs');
// 3rd party libraries used to track events in the journal file
const { Tail } = require('tail');
const chokidar = require('chokidar');
class JournalError extends Error {
constructor(message) {
super(message);
}
}
class EliteJournalWatcher extends EventEmitter {
options = {};
tailInstance;
chokidarInstance;
currentFile;
constructor(options) {
super()
// Assign values to option property and use the given value. If undefined, use the default value
options = options || {};
this.options.path = options.path || path.join(os.homedir(), 'Saved Games/Frontier Developments/Elite Dangerous')
}
getLatestJournalFile() {
let files = fs.readdirSync(this.options.path);
files = files.filter(e => e.startsWith('Journal.'));
files.sort();
files.reverse();
return files[0];
}
start() {
if (this.tailInstance) {
throw new JournalError("Listener is already listening.")
}
const file = this.getLatestJournalFile();
this.currentFile = file;
this.tailInstance = new Tail(path.join(this.options.path, file));
this.tailInstance.on('line', this.tailListener);
if (this.chokidarInstance == null) {
this.chokidarInstance = chokidar.watch('.', {cwd: this.options.path});
this.chokidarInstance.on('add', this.chokidarListener.bind(this));
} else {
this.chokidarInstance.add('.');
}
}
stop() {
if (!this.tailInstance) {
throw new JournalError("Listener is not running.");
}
if (this.chokidarInstance) {
this.chokidarInstance.unwatch('.');
}
this.tailInstance.unwatch();
this.tailInstance = null;
}
tailListener(data) {
var jsonData = JSON.parse(data);
this.emit(jsonData.event, jsonData);
}
chokidarListener(path, stats) {
if (path.startsWith('Journal.') && path != this.currentFile) {
this.stop();
this.start();
}
}
}
module.exports.EliteJournalWatcher = EliteJournalWatcher;
module.exports.JournalError = JournalError;