Javascript 从 gulp 运行 shell 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29511491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:29:22  来源:igfitidea点击:

Running a shell command from gulp

javascriptgulp

提问by Ben Aston

I would like to run a shell command from gulp, using gulp-shell. I see the following idiom being used the gulpfile.

我想从 gulp 运行一个 shell 命令,使用gulp-shell. 我看到 gulpfile 使用了以下习语。

Is this the idiomatic way to run a command from a gulp task?

这是从 gulp 任务运行命令的惯用方法吗?

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

回答by ddprrt

gulp-shellhas been blacklisted. You should use gulp-execinstead, which has also a better documentation.

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

For your case it actually states:

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

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);
  });
})

回答by AutoSponge

The new way to do this that keeps console output the same (e.g., with colors):

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

see: https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

请参阅: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);
  });
});

回答by birnbaum

With gulp 4your tasks can directly return a child process to signal task completion:

使用gulp 4,您的任务可以直接返回子进程以表示任务完成:

'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

gulp-v4-running-shell-commands.md

回答by azerafati

You could simply do this:

你可以简单地这样做:

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;
});