Start your MAMP dev server with Grunt

Posted on

I just started a new project that requires a PHP server, but the built-in PHP server used by grunt-php is not beefy enough. Instead, I need to run the MAMP server in order to test it.

To get around this, I installed the excellent grunt-exec plugin which allows Grunt to run arbitrary commands. Add these tasks to your Gruntfile to allow you to start and stop the MAMP server:

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

Of course, you can name the tasks however you like. serverup and serverdown just made the most sense to me.

Now, edit your Grunt task containing a watch task. Add exec:serverup before the watch and exec:serverdown after the watch. Here’s an example:

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

UPDATE: Although this works for bringing the server up, it does not work for taking it down. Once you end the task in your shell, none of the subsequent Grunt tasks fire, so the serverdown task never runs.

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

Include this outside the module.exports for Grunt. This will watch for the SIGINT event — which fires when you use Ctrl-C to end your task — and will bring the server down when that event fires.

You can remove the serverdown task as it never fires anyway.

Leave a Reply

Your email address will not be published.