问题
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.
回答1:
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());
});
来源:https://stackoverflow.com/questions/51715828/how-can-i-run-a-shell-command-inside-of-a-gulp-task-and-detect-when-its-done