4

I have a PHP-based project that won't run on grunt-php. Instead, I use grunt-exec to run my MAMP server for development.

exec: {
  serverup: {
    command: '/Applications/MAMP/bin/start.sh'
  },
  serverdown: {
    command: '/Applications/MAMP/bin/stop.sh'
  }
}

In my custom development task, I run the MAMP start script just before my watch task. Then, I'm trying to stop the MAMP server after I've exited the watch task.

grunt.registerTask('default', ['jshint', 'concat', 'compass:dev', 'exec:serverup', 'watch', 'exec:serverdown']);

However, if I exit the task with Ctrl-C, the exec:serverdown task never seems to run. Is there any way to make this work? Since the server never goes down, that port is tied up until I manually run the stop script, and I get errors if I try to run the default task again before bringing it down.

If not, is there some other way I could accomplish the same thing?

raddevon
  • 3,290
  • 4
  • 39
  • 49
  • Do you mind sharing why it won't work with grunt-php? – Sindre Sorhus Jul 19 '13 at 23:13
  • @SindreSorhus I don't know exactly. I'm developing a theme for [Koken](http://koken.me/). I started out trying to use grunt-php, but I couldn't get the install to complete. I posted on the Koken forums and was told by a dev it wouldn't work with the built-in PHP server which is apparently what grunt-php uses. He didn't say why. – raddevon Jul 20 '13 at 02:16

1 Answers1

4

You could listen on SIGINT and run the script:

var exec = require('child_process').exec;
process.on('SIGINT', function () {
    exec('/Applications/MAMP/bin/stop.sh', function () {
        process.exit();
    });
});

module.exports = function (grunt) {};
Sindre Sorhus
  • 62,972
  • 39
  • 168
  • 232
  • Thank you for the answer. Looks promising. I will try it out soon and report back. – raddevon Jul 18 '13 at 18:38
  • I'm having some trouble with this. I'm not sure exactly where this should go in my Gruntfile. If I include it inside `module.exports = function (grunt) {...}`, I can no longer end the task with Ctrl-C. If I put it outside that function, I get `Fatal error: grunt is not defined`. – raddevon Jul 19 '13 at 02:02
  • That allows me to exit the task, but the server is still up when all is said and done. I can run `grunt exec:serverdown` manually, and the server does go down. – raddevon Jul 19 '13 at 12:17
  • Seems like grunt.task.run is async without having a callback, which makes it run process.exit() before being able to run the task. I've updated the answer with another solution. – Sindre Sorhus Jul 19 '13 at 23:19