Unknown
This commit is contained in:
31
scripts/lib/data-file.js
Normal file
31
scripts/lib/data-file.js
Normal file
@ -0,0 +1,31 @@
|
||||
export class DataFile {
|
||||
/**
|
||||
* Read & write data to a JSON file.
|
||||
*
|
||||
* @param {NS} ns - Bitburner API
|
||||
* @param path - Path to config file
|
||||
*/
|
||||
constructor(ns, path) {
|
||||
this.ns = ns;
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load data file
|
||||
*
|
||||
* @returns {Promise<any>} - Saved data
|
||||
*/
|
||||
async load() {
|
||||
return JSON.parse(await this.ns.read(this.path) || 'null');
|
||||
}
|
||||
|
||||
/**
|
||||
* Save data to file
|
||||
*
|
||||
* @param values - Data to save
|
||||
* @returns {Promise<void>} - Save complete
|
||||
*/
|
||||
async save(values) {
|
||||
await this.ns.write(this.path, JSON.stringify(values), 'w');
|
||||
}
|
||||
}
|
42
scripts/lib/port-helper.js
Normal file
42
scripts/lib/port-helper.js
Normal file
@ -0,0 +1,42 @@
|
||||
export class PortHelper {
|
||||
/**
|
||||
*
|
||||
* @param ns
|
||||
* @param port
|
||||
* @param host
|
||||
*/
|
||||
constructor(ns, port, host) {
|
||||
this.ns = ns;
|
||||
this.host = host;
|
||||
this.portNum = port;
|
||||
this.port = ns.getPortHandle(port);
|
||||
this.callbacks = {};
|
||||
}
|
||||
|
||||
check() {
|
||||
const pending = [];
|
||||
while(!this.port.empty()) pending.push(this.port.read());
|
||||
pending.filter(p => {
|
||||
try {
|
||||
const payload = JSON.parse(p);
|
||||
if(this.callbacks[payload.subject]) return !this.callbacks[payload.subject](payload.value);
|
||||
if(this.callbacks['*']) return !this.callbacks['*'](payload.value);
|
||||
return true;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}).forEach(p => this.port.write(p));
|
||||
}
|
||||
|
||||
subscribe(subject, callback) { if(typeof callback == 'function') this.callbacks[subject] = callback; }
|
||||
|
||||
send(subject, value) {
|
||||
this.ns.writePort(this.portNum, JSON.stringify({
|
||||
from: this.host,
|
||||
subject,
|
||||
value
|
||||
}));
|
||||
}
|
||||
|
||||
unsubscribe(subject) { delete this.callbacks[subject]; }
|
||||
}
|
Reference in New Issue
Block a user