@signalk/streams
Version:
Utilities for handling streams of Signal K data
62 lines (61 loc) • 2.16 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const readline_1 = require("readline");
const stream_1 = require("stream");
class N2kAnalyzer extends stream_1.Transform {
analyzerOutEvent;
analyzerProcess;
pipeTo = null;
constructor(options) {
super({ objectMode: true });
this.analyzerOutEvent = options.analyzerOutEvent ?? 'N2KAnalyzerOut';
if (process.platform === 'win32') {
this.analyzerProcess = (0, child_process_1.spawn)('cmd', ['/c', 'analyzer -json -si -camel']);
}
else {
this.analyzerProcess = (0, child_process_1.spawn)('sh', ['-c', 'analyzer -json -si -camel']);
}
this.analyzerProcess.stderr?.on('data', (data) => {
console.error(data.toString());
});
this.analyzerProcess.on('close', (code) => {
console.error('Analyzer process exited with code ' + code);
});
const linereader = (0, readline_1.createInterface)(this.analyzerProcess.stdout, this.analyzerProcess.stdin);
linereader.on('line', (data) => {
try {
const parsed = JSON.parse(data);
if (parsed.version) {
console.log('Connected to analyzer v' + parsed.version);
return;
}
this.push(parsed);
options.app.emit(this.analyzerOutEvent, parsed);
}
catch (ex) {
console.error(data);
if (ex instanceof Error) {
console.error(ex.stack);
}
}
});
}
_transform(chunk, encoding, done) {
this.analyzerProcess.stdin?.write(chunk.toString() + '\n');
done();
}
pipe(pipeTo) {
this.pipeTo = pipeTo;
return super.pipe(pipeTo);
}
end() {
console.log('end, killing child analyzer process');
this.analyzerProcess.kill();
if (this.pipeTo) {
this.pipeTo.end();
}
return this;
}
}
exports.default = N2kAnalyzer;