运行 来自 gulp 的 shell 命令

Running a shell command from gulp

我想 运行 来自 gulp 的 shell 命令,使用 gulp-shell。我看到 gulp 文件中使用了以下成语。

这是 运行 来自 gulp 任务的命令的惯用方式吗?

var cmd = 'ls';
gulp.src('', {read: false})
    .pipe(shell(cmd, {quiet: true}))
    .on('error', function (err) {
       gutil.log(err);
});

gulp-shell 已被列入黑名单。您应该改用 gulp-exec,它也有更好的文档。

对于你的情况,它实际上指出:

Note: If you just want to run a command, just run the command, don't use this plugin:

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

gulp.task('task', function (cb) {
  exec('ping localhost', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    cb(err);
  });
})

保持控制台输出相同(例如,颜色)的新方法:

参见:https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

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

gulp.task('my-task', function (cb) {
  var cmd = spawn('cmd', ['arg1', 'agr2'], {stdio: 'inherit'});
  cmd.on('close', function (code) {
    console.log('my-task exited with code ' + code);
    cb(code);
  });
});

使用 gulp 4 你的任务可以直接 return 一个子进程来通知任务完成:

'use strict';

var cp = require('child_process');
var gulp = require('gulp');

gulp.task('reset', function() {
  return cp.execFile('git checkout -- .');
});

gulp-v4-running-shell-commands.md

您可以简单地这样做:

const { spawn } = require('child_process');
const gulp = require('gulp');

gulp.task('list', function() {
    const cmd = spawn('ls');
    cmd.stdout.on('data', (data) => {
        console.log(`stdout: ${data}`);
    });
    return cmd;
});

根据 Gulp 的文档,您可以 运行 像 echo 这样的命令:

const cp = require('child_process');

function childProcessTask() {
  return cp.exec('echo *.js');
}

exports.default = childProcessTask;

exec 接受一个将由 shell 解析的字符串,默认情况下它会静音输出。

我个人更喜欢使用 child_process.spawnspawn 采用命令名称,然后是参数列表。如果您使用选项 stdio: 'inherit' 它不会吞下它的输出。

function childProcessTask() {
  return cp.spawn('echo', ['one', 'two'], {stdio: 'inherit'});
}

参考文献: