Kivol Kivol - 1 month ago 6x
Node.js Question

Running grunt task with api, without command line

I want to create and run grunt task in node.js code for test use.

var foo = function() {
var grunt = require("grunt");

var options = {"blahblah": null} // ...creating dynamic grunt options, such as concat and jshint
grunt.registerTask('default', [/*grunt subtasks*/]);

But this doesn't work. Grunt doesn't seem to run any task. I'm almost sure that there is some API to run grunt task externally without command line, but don't know how to do it.

Is there any way to do it?


You can. I don't know why anyone would need to do this as currently Grunt is a command line tool. WARNING: I don't recommend running Grunt in this way. But here it is:

var grunt = require('grunt');

// hack to avoid loading a Gruntfile
// You can skip this and just use a Gruntfile instead
grunt.task.init = function() {};

// Init config
  jshint: {
    all: ['index.js']

// Register your own tasks
grunt.registerTask('mytask', function() {
  grunt.log.write('Ran my task.');

// Load tasks from npm

// Finally run the tasks, with options and a callback when we're done
grunt.tasks(['mytask', 'jshint'], {}, function() {
  grunt.log.ok('Done running tasks.');