public
Last active

Simple snippet for cross-platform .pid management in NodeJS. I use it for managing NodeJS apps with supervisord and monit

  • Download Gist
pid.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
//
// Usage: require('./pid')("myapp");
//
var fs = require('fs');
 
module.exports = function(appname){
process.title = appname;
 
var PID_FILE = "/usr/local/var/run/"+process.title+".pid";
 
fs.writeFileSync(PID_FILE, process.pid+"\n");
 
process.on("uncaughtException", function(err) {
console.error("[uncaughtException]", err);
return process.exit(1);
});
 
process.on("SIGTERM", function() {
console.log("SIGTERM (killed by supervisord or another process management tool)");
return process.exit(0);
});
 
process.on("SIGINT", function() {
console.log("SIGINT");
return process.exit(0);
});
 
process.on("exit", function() {
return fs.unlink(PID_FILE);
});
};
pid_management.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#
# The following snippet must be inserted at the top of your main js file
#
 
process.title = "MyApp"
PID_FILE = "/usr/local/var/run/#{process.title}.pid"
fs = require("fs")
 
fs.writeFileSync PID_FILE, "#{process.pid}\n"
 
process.on "uncaughtException", (err) ->
console.error "[uncaughtException]", err
process.exit 1
 
process.on "SIGTERM", ->
console.log "SIGTERM (killed by supervisord or another process management tool)"
process.exit 0
 
process.on "SIGINT", ->
console.log "SIGINT"
process.exit 0
 
process.on "exit", ->
console.log('Exiting...')
fs.unlink PID_FILE
 
#
# Your code start here
#
 
setInterval (->), 1000
pid_management.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
//
// The following snippet must be inserted at the top of your main js file
//
 
process.title = "MyApp";
 
var PID_FILE = "/usr/local/var/run/"+process.title+".pid"
, fs = require('fs');
 
fs.writeFileSync(PID_FILE, process.pid+"\n");
 
process.on("uncaughtException", function(err) {
console.error("[uncaughtException]", err);
return process.exit(1);
});
 
process.on("SIGTERM", function() {
console.log("SIGTERM (killed by supervisord or another process management tool)");
return process.exit(0);
});
 
process.on("SIGINT", function() {
console.log("SIGINT");
return process.exit(0);
});
 
process.on("exit", function() {
return fs.unlink(PID_FILE);
});
 
//
// Your code start here
//
 
setInterval(function(){}, 1000);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.