47 lines
1.0 KiB
JavaScript
47 lines
1.0 KiB
JavaScript
import { spawn } from "child_process";
|
|
|
|
export class Router {
|
|
|
|
constructor () {
|
|
this.callbacks = { };
|
|
this.stdoutBuffer = "";
|
|
this.onmessage = null;
|
|
}
|
|
|
|
async callMethod ( method, params = { } ) {
|
|
const child = spawn( "python3", [ "index.py", method, JSON.stringify( params ) ] );
|
|
|
|
return await new Promise( ( resolve, reject ) => {
|
|
let result = "";
|
|
|
|
child.stdout.on( "data", ( data ) => {
|
|
const lines = data.toString().split( "\n" );
|
|
|
|
for ( const line of lines ) {
|
|
if ( line.startsWith( "__STREAM__" ) ) {
|
|
const payload = line.substring( 10 ).trim();
|
|
|
|
if ( this.onmessage ) {
|
|
this.onmessage( JSON.parse( payload ) );
|
|
}
|
|
} else if ( line.trim() ) {
|
|
result += line.trim();
|
|
}
|
|
}
|
|
} );
|
|
|
|
child.stderr.on( "data", ( err ) => {
|
|
reject( new Error( err.toString() ) );
|
|
} );
|
|
|
|
child.on( "close", () => {
|
|
try {
|
|
resolve( JSON.parse( result ) );
|
|
} catch ( err ) {
|
|
reject( new Error( "Failed to parse response: " + result ) );
|
|
}
|
|
} );
|
|
} );
|
|
}
|
|
}
|