diff --git a/bin/cli b/bin/cli index 107d0a9ba..002288648 100755 --- a/bin/cli +++ b/bin/cli @@ -7,7 +7,6 @@ const program = require('commander'); const pkg = require('../package.json'); const dotenv = require('dotenv'); -const fs = require('fs'); const util = require('../util'); //============================================================================== @@ -32,36 +31,7 @@ if (program.config) { // If the `--pid` flag is used, put the current pid there. if (program.pid) { - let pidPath = program.pid; - - if (!/\//.test(pidPath)) { - if (!/\.pid/.test(pidPath)) { - pidPath += '.pid'; - } - pidPath = `/tmp/${pidPath}`; - } - - fs.writeFile(pidPath, `${process.pid.toString()}\n`, (err) => { - if (err) { - console.error(`Can't write PID file: ${err}`); - throw err; - } - - // Add the cleanup for the fs onto the shutdown. - util.onshutdown([ - () => new Promise((resolve, reject) => { - - // Remove the pid file. - fs.unlink(pidPath, (err) => { - if (err) { - return reject(err); - } - - return resolve(); - }); - }) - ]); - }); + util.pid(program.pid); } // Perform rewrites to the runtime environment variables based on the contents diff --git a/util.js b/util.js index 261b66f85..585cfdcb7 100644 --- a/util.js +++ b/util.js @@ -1,4 +1,6 @@ const debug = require('debug')('talk:util'); +const fs = require('fs'); + const util = module.exports = {}; /** @@ -45,6 +47,43 @@ util.onshutdown = (jobs) => { util.toshutdown = util.toshutdown.concat(jobs); }; +/** + * Register a PID file to be maintained for the lifespan of the process. + * @param {String} path path to the PID file to create + */ +util.pid = (path) => { + if (!/\//.test(path)) { + if (!/\.pid/.test(path)) { + path += '.pid'; + } + path = `/tmp/${path}`; + } + + const pid = `${process.pid.toString()}\n`; + + fs.writeFile(path, pid, (err) => { + if (err) { + console.error(`Can't write PID file: ${err}`); + throw err; + } + + // Add the cleanup for the fs onto the shutdown. + util.onshutdown([ + () => new Promise((resolve, reject) => { + + // Remove the pid file. + fs.unlink(path, (err) => { + if (err) { + return reject(err); + } + + return resolve(); + }); + }) + ]); + }); +}; + // Attach to the SIGTERM + SIGINT handles to ensure a clean shutdown in the // event that we have an external event. SIGUSR2 is called when the app is asked // to be 'killed', same procedure here.