Created
February 13, 2022 15:06
-
-
Save lenconda/fd6d2773ca1cedd5bd7b7ab80197e71e to your computer and use it in GitHub Desktop.
Daemonize & keep alive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const child_process = require('child_process'); | |
const daemon = (pathname) => { | |
const child = child_process.fork(pathname); | |
child.unref(); | |
return child; | |
}; | |
module.exports = daemon; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cluster = require('cluster'); | |
const _ = require('lodash'); | |
const keepalive = async (cb) => { | |
if (cluster.isMaster) { | |
cluster.fork(); | |
cluster.on('exit', () => { | |
cluster.fork(); | |
}); | |
} | |
if (cluster.isWorker && _.isFunction(cb)) { | |
await cb(); | |
} | |
}; | |
module.exports = keepalive; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const daemon = require('./daemon'); | |
const path = require('path'); | |
const child = daemon(path.resolve(__dirname, './test.service.js')); | |
console.log(child.pid); | |
process.exit(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const keepalive = require('./keepalive'); | |
const fs = require('fs'); | |
const path = require('path'); | |
keepalive(async () => { | |
const logFilePathname = path.resolve(__dirname, './info.log'); | |
fs.appendFileSync(logFilePathname, 'new process\n', { encoding: 'utf-8' }); | |
for (let i = 0; i < 10; i += 1) { | |
fs.appendFileSync(logFilePathname, new Date().toISOString() + '\n', { encoding: 'utf-8' }); | |
await new Promise((resolve) => setTimeout(() => resolve(), 500)); | |
} | |
process.exit(1); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment