Skip to content

Instantly share code, notes, and snippets.

@maksimr
Last active October 13, 2023 20:55
Show Gist options
  • Save maksimr/6318a88971fa13057a2f751740367179 to your computer and use it in GitHub Desktop.
Save maksimr/6318a88971fa13057a2f751740367179 to your computer and use it in GitHub Desktop.
node background-process
async function register(message) {
await import(message.path);
process.send({ type: 'registred' });
}
process.on('message', (message) => {
switch (message.type) {
case 'register':
return register(message);
case 'ping':
return process.send({ type: 'pong', timestamp: Date.now() });
}
});
import { fork } from 'child_process';
import EventEmitter from 'events';
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const daemonPath = `${__dirname}/daemon.mjs`;
export class BackgroundProcess extends EventEmitter {
constructor(modulePath, options = {}) {
super();
this.modulePath = modulePath;
this.pingIntervalMs = options.pingIntervalMs ?? 60000;
this.pingTimeoutMs = options.pingTimeoutMs ?? 30000;
}
start() {
this.stop();
this.forkProcess = fork(daemonPath);
let pingTimeout;
const pintInterval = setInterval(() => {
this.forkProcess.send({ type: 'ping', timestamp: Date.now() });
pingTimeout = setTimeout(() => {
console.error('ping timeout, restarting process');
return this.start();
}, this.pingTimeoutMs);
}, this.pingIntervalMs);
this.forkProcess.on('message', (message) => {
switch (message.type) {
case 'pong':
clearTimeout(pingTimeout);
break;
case 'registred':
console.log('registred', this.modulePath);
break;
}
});
this.forkProcess.on('exit', () => {
clearTimeout(pingTimeout);
clearInterval(pintInterval);
this.emit('exit');
});
console.log('register', this.modulePath);
this.forkProcess.send({
type: 'register',
path: path.resolve(this.modulePath)
});
}
stop() {
if (this.forkProcess) {
this.forkProcess.kill();
}
}
pid() {
if (this.forkProcess) {
return this.forkProcess.pid;
}
}
isRunning() {
return !this.forkProcess.killed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment