gulp:如何执行shell命令并获取输出

时间:2016-09-18 06:34:03

标签: gulp

我需要运行shell命令并将结果写入json文件:

const Shell = require('gulp-shell');

gulp.task('build-info', () => {
  gulp.src('./app/_bundle_info_.json')
    .pipe(jeditor((json) => {
      var buildNumber = Shell.task([
        'git rev-list --count HEAD'
      ]);
      // !!!: I can't get the output of `git rev-list --count HEAD ` via `buildNumber`
      json.buildNumber = buildNumber;
      return json;
    }))
    .pipe(gulp.dest("./app"));

});

我使用gulp-shell来运行shell命令,但我无法从git rev-list --count HEAD获取输出。

1 个答案:

答案 0 :(得分:5)

如果需要命令的直接输出,可以使用Node的child_process.execSync,然后在其上调用toString。

例如:

var execSync = require('child_process').execSync;
console.log(execSync('pwd').toString());

对于您的代码,它看起来像这样:

var execSync = require('child_process').execSync;

gulp.task('build-info', () => {
  gulp.src('./app/_bundle_info_.json')
    .pipe(jeditor((json) => {
      var buildNumber = execSync('git rev-list --count HEAD').toString();
      // !!!: I can't get the output of `git rev-list --count HEAD ` via `buildNumber`
      json.buildNumber = buildNumber;
      return json;
    }))
    .pipe(gulp.dest("./app"));

});

有关child_process.execSync的详细信息,请参阅此处:https://nodejs.org/api/child_process.html#child_process_child_process_execsync_command_options

对于您或其他任何观看此问题的人来说,gulp-shell也被gulp团队列入黑名单:https://github.com/gulpjs/plugins/blob/master/src/blackList.json