Skip to content

Instantly share code, notes, and snippets.

@getify
Created October 29, 2013 20:06
Show Gist options
  • Save getify/7221630 to your computer and use it in GitHub Desktop.
Save getify/7221630 to your computer and use it in GitHub Desktop.
shutting down a `forever`-started server when CTRL+C quitting a grunt-watch task
module.exports = function(grunt) {
var path = require("path");
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
forever: {
options: {
index: path.join(__dirname,"server.js")
}
},
watch: {
...
}
});
// Load the plugins
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks('grunt-forever');
// define tasks
grunt.registerTask("server-shutdown-listener",function(){
process.on("SIGINT",function(){
console.log("");
console.log("Shutting down server...");
require("child_process").exec(
path.join(__dirname, "node_modules", ".bin", "forever stop \"" + path.join(__dirname,"server.js") + "\""),
function(err,stdout,stderr) {
console.log(stdout);
if (stderr) {
console.log(stderr);
}
if (err !== null) {
console.log(err);
}
console.log("Server shutdown complete.");
process.exit();
}
);
});
});
grunt.registerTask("dev", [
"forever:start",
"server-shutdown-listener",
"watch"
]);
};
@shama
Copy link

shama commented Oct 30, 2013

Try this:

grunt.registerTask("server-shutdown-listener",function(step){
  var name = this.name;
  if (step === 'exit') process.exit();
  else {
    process.on("SIGINT",function(){
      grunt.log.writeln("").writeln("Shutting down server...");
      grunt.task.run(["forever:stop", name + ":exit"]);
      grunt.task.current.async()();
    });
  }
});

EDIT: Updated to use this.name to make it a bit more portable.

@getify
Copy link
Author

getify commented Oct 30, 2013

@shama <3 <3 <3 thanks so much! works perfectly!

@blaskovicz
Copy link

Does this still work in the latest versions? It was working but no longer seems to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment