Moved PID into util.js

This commit is contained in:
Wyatt Johnson
2017-01-25 11:57:40 -07:00
parent edf9ced454
commit 91402a3e8b
2 changed files with 40 additions and 31 deletions
+1 -31
View File
@@ -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
+39
View File
@@ -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.