Skip to content

Instantly share code, notes, and snippets.

@kosuke-suzuki
Last active September 24, 2020 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosuke-suzuki/95f951901e71c65e232d5993caa4853e to your computer and use it in GitHub Desktop.
Save kosuke-suzuki/95f951901e71c65e232d5993caa4853e to your computer and use it in GitHub Desktop.
Dummy Service in Python and its wrapper in JavaScript
import time
import pathlib
import random
time.sleep(random.randrange(1, 10, 1))
file = pathlib.Path('./finish')
file.touch()
const { spawn } = require('child_process');
const fs = require('fs');
const fsPromises = fs.promises;
class SomeService {
_proc;
_callbacks;
_intervals;
constructor() {
this._proc = null;
this._callbacks = {};
this._intervals = [];
}
_monitor() {
const interval = setInterval(() => {
fsPromises.access('finish')
.then(() => {
return fsPromises.unlink('finish')
.then(() => {
this._stopMonitor();
if (this._callbacks.ready != null) {
this._callbacks.ready();
this._callbacks.ready = null;
}
});
})
.catch((err) => {
console.log(err);
console.log('Proc is not ready yet...');
});
}, 1 * 1000);
this._intervals.push(interval);
}
_stopMonitor() {
this._intervals.forEach((interval) => clearInterval(interval));
this._intervals = [];
}
onReady(callback) {
this._callbacks.ready = callback;
}
start() {
this._monitor();
this._proc = spawn('python3', ['dummy_service.py']);
}
stop() {
this._proc.kill();
this._stopMonitor();
}
}
module.exports = SomeService;
const SomeService = require('./SomeService');
const startService = (timeoutSec) => {
const service = new SomeService();
return new Promise((resolve, reject) => {
service.onReady(() => {
clearTimeout(onTimedout);
resolve(service);
});
service.start();
const onTimedout = setTimeout(() => {
service.stop();
reject(`Proc did not launch within ${timeoutSec} seconds.`);
}, timeoutSec * 1000);
});
};
startService(5)
.then(() => {
console.log('Proc launched successfully.');
}, () => {
console.log('Attempt to launch proc was timed out.');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment