Serge van den Oever's weblog

Run Gulp 4 tasks programmatically from NodeJS

Sun Nov 01 2020 • ☕️ 1 min read • you like my writing? Buy me a coffee

I want to use the power of the Gulp functions like the series(), parallel(), src(), dest(), pipe(), the globbing, an the plugin model within my node application. And it is easy to do. But I can tell you… it took me hours to find out, and the missing link was that I forgot two brackets: (). The gulp.series() and gulp.parallel() give back a function that must be executed:

const {series} = require('gulp');

// simple gulp task
const helloTask = done => {
  console.log('hello from helloTask');
  done();
}

console.log('start');
series(helloTask)();
console.log('end');

The import part is series(helloTask)(). But the output was still in the wrong order:

start
end
hello from helloTask

This is because everything in Gulp is asynchronous. We need to wait for the completion of the series before continuing. This can be achieved using a promise, and awaiting the promise. If we want to await a promise we need to execute that code from an async function:

const gulp = require('gulp');

// simple gulp task
const helloTask = done => {
  console.log('hello from helloTask');
  done();
}

async function gulpTaskRunner(task) {
  return new Promise(function (resolve, reject) {
    gulp.series(task, (done) => {
      console.log("Gulp task completed");
      resolve();
      done();
    })();
  });
}

async function app() {
  console.log('start');
  await gulpTaskRunner(helloTask);
  console.log('end');
}

app();

In this way we can create a simple gulpTaskRunner() function that can be executed from within your node application.

And the output is now as follows:

start
hello from helloTask
Gulp task completed
end

Discuss on TwitterEdit on GitHub

This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. You are free to share and adapt this work for non-commercial purposes, provided you give appropriate credit, provide a link to the license, and indicate if changes were made. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/4.0/.

Serge van den Oever's weblog

Serge van den Oever

Personal blog by Serge van den Oever - als je maar lol hebt...
X: @svdoever
LinkedIn: Serge van den Oever - articles on LinkedIn
GitHub: svdoever

Technology Consultant @ Macaw
2021-2024 Sitecore Technology MVP