Where is Gulp's API?

March 15, 2015

Gulp.js is an awesome build system that helps with automating common tasks during development. Despite the benefits, there are times when the standard way of running the tasks, via the command line interface, is not enough and you would want to embed gulp in another application and run the tasks programmatically... So, this raises the question where is the Gulp API?

Lets consider that we have the following gulp setup:

var gulp = require("gulp");

gulp.task("dependency", function () {
  // do something before trigger
});

gulp.task("trigger", ["dependency"], function () {
  // do something
});

The most interesting features when building a front end, which uses gulp programmatically, is to be aware of the task execution state. A closer look at the source reveals that under the hood a gulp object is just an orchestrator, and all the orchestrator's goodies are directly available to gulp as well. Therefore, gulp emits events when starting a task sequence, and on the beginning and end of each task in the respective sequence:

gulp.on("start", function (e) {
  // task sequence started
  console.log(e);
});

gulp.on("task_start", function (e) {
  // task started
  console.log(e);
});

gulp.on("task_stop", function (e) {
  // task ended
  console.log(e);
});

Now with the events registered we can run the trigger task as follows:

gulp.start("trigger");

The result contains the sequence of tasks as well as the progress information including the time required to run each task:

{ message: 'seq: dependency,trigger' }
{ task: 'dependency', message: 'dependency started' }
{ task: 'dependency',
message: 'dependency sync',
duration: 0.000072076,
hrDuration: [ 0, 72076 ] }
{ task: 'trigger', message: 'trigger started' }
{ task: 'trigger',
message: 'trigger sync',
duration: 0.000020074,
hrDuration: [ 0, 20074 ] }

So, the answer to where is the Gulp API? is... under the hood, in the orchestrator.


;