srquinn srquinn - 1 month ago 11x
Node.js Question

Programmatically controlling Grunt.js

I would like to have access to the many available plugins and tasks in the grunt ecosystem to make my life easier, but I would like control over when and how each task is run. Most importantly, I want a way to run grunt tasks programmatically instead of running

from the command line in a folder with a
. So I started poking around
for a "way in."

From the source code of GruntJS:

// Expose the task interface. I've never called this manually, and have no idea
// how it will work. But it might.
grunt.tasks = function(tasks, options, done) {

As you can see, Mr. Allman cautions us about the interface... my question is, has anyone gotten this to work?

My experiments, so far, have led me to believe the best way to programmatically control grunt is by mimicking the command line call with a child process:

$ npm install grunt-cli //notice no -g flag

// From runner.js
var exec =require('child_process').exec

exec('node_modules/.bin/grunt-cli tasks to run', {
cwd: 'path/to/directory/with/a/gruntfile'
}, function() { /* do stuff here */ });

This seems dirty so I'm thinking about simply writing my own task-runner that exposes an interface for grunt tasks. However, I don't want to dup work if someone has had success with
despite Mr. Allman's warnings.


The obvious answer seems like it should be write a grunt task to do whatever you want to do :)

Then you can use to control other grunt tasks:

You can also update their configs dynamically before running them very easily by messing with grunt.config

There's also this answer which may answer your question: How can I run a grunt task from within a grunt task?

Also check out grunt.task.start() which is not publicy documented, but it seems to kick off all of the tasks (hat tip: @jibsales)