How can I run a shell command inside of a gulp task and detect when it's done?
Asked Answered
M

1

4

I'm trying to run a shell command inside of a gulp task using child_process.spawn.

I have to detect when the task is done running so I'm using stdout to check for a specific string that I emit at the end of the command, but for some reason it doesn't look like my string is being emitted:

// gulp 3.9.1
var gulp = require('gulp');
var spawn = require('child_process').spawn;

gulp.task('my-task', function(cb) {
  var command = ''; // construct my shell command here
  var end = 'end_of_command';
  var command = command + '; echo ' + end; // add special string to look for

  var cmd = spawn(command, { shell: true });

  cmd.stdout.on('data', function(data) {
    if (data.includes(end)) {
      return cb();
    }
  });
});

For some reason my echo statement isn't emitting and so the if statement is not being passed.

Where am I going wrong?

I should also note that when I run this command directly in my shell rather than through the gulp task, it runs fine and the expected output is visible.

Malnutrition answered 6/8, 2018 at 21:23 Comment(3)
Are you doing it this way on purpose? Because waiting for end_of_command output is really weird way to do that.Gibun
For some reason I can't find the question that I was referencing for this idea that had the solution of looking for an "end string". Is there a better way to detect the end/exiting of a shell command in a gulp task?Malnutrition
You didn't find anything on command execution because the problem isn't specific to Gulp.Gibun
G
4

Both Gulp and child_process asynchronous functions use Node-style error-first callbacks.

spawn is intended for processing streams during command execution. If all is needed is to wait until a command is finished, exec and execFile do that:

var gulp = require('gulp');
var exec = require('child_process').exec;

gulp.task('my-task', function(cb) {
  exec('cmd', cb);
});

It may be more intricate with spawn because it also allows to handle exit codes:

var gulp = require('gulp');
var spawn = require('child_process').spawn;

gulp.task('my-task', function(cb) {
  spawn('cmd', [], {})
  .on('error', cb)
  .on('close', code => code ? cb(new Error(code)) : cb());
});
Gibun answered 6/8, 2018 at 22:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.