如何在gulp中运行bash命令?

50

我希望在gulp.watch函数的结尾添加一些bash命令,以加速我的开发速度。因此,我想知道这是否可能。谢谢!

3个回答

77

我会选择:

var spawn = require('child_process').spawn;
var fancyLog = require('fancy-log');
var beeper = require('beeper');

gulp.task('default', function(){

    gulp.watch('*.js', function(e) {
        // Do run some gulp tasks here
        // ...

        // Finally execute your script below - here "ls -lA"
        var child = spawn("ls", ["-lA"], {cwd: process.cwd()}),
            stdout = '',
            stderr = '';

        child.stdout.setEncoding('utf8');

        child.stdout.on('data', function (data) {
            stdout += data;
            fancyLog(data);
        });

        child.stderr.setEncoding('utf8');
        child.stderr.on('data', function (data) {
            stderr += data;
            fancyLog.error(data));
            beeper();
        });

        child.on('close', function(code) {
            fancyLog("Done with exit code", code);
            fancyLog("You access complete stdout and stderr from here"); // stdout, stderr
        });


    });
});

这里实际上没有使用"gulp" - 主要是使用子进程http://nodejs.org/api/child_process.html,并将结果欺骗到fancy-log中。


3
经过一些关于子进程的研究后,我最终使用了 child_process.exec 达成了我的目标。感谢你提供的 Node 资源! - houhr
27
感谢您实际回答他的问题,而不是发送插件链接作为答复。 - Andy Ferra
8
虽然我可以理解你可能不想使用插件,但我认为我的回答仍然解决了问题。 - Erik
我有同样的问题,你的答案比重新设计这个老生常谈的轮子更符合我的需求(这并不是贬低Mangled的回答)。 - Adrian Günter

45

6
虽然有其他方法(如gulp-exec和gulp-spawn),但gulp-shell会立即打印命令的输出,这通常是需要的。 - jmu
4
现在还有一个名为gulp-run的工具,它拥有更干净和更直观的界面。在我看来,这个工具更易用。 - Adrian Günter
14
gulp-shell已被列入黑名单,详情请参见https://github.com/gulpjs/plugins/blob/master/src/blackList.json。 - Nico Schlömer
2
它被“列入黑名单”是因为与gulp-exec存在一些重叠--并不是说这两个插件有任何问题。https://github.com/sun-zheng-an/gulp-shell/issues/1 - Erik
4
在gulp中运行bash命令不需要任何插件,只需直接使用Node的 child_process 。这就是为什么那些插件被列入黑名单的原因。 - demisx
显示剩余2条评论

1
最简单的解决方案就是这样的:

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

gulp.task('launch-ls',function(done) {
   child.spawn('ls', [ '-la'], { stdio: 'inherit' });
});

它不使用节点流和Gulp管道,但它能完成工作。

done从未被调用。如果其他脚本在它之前或之后应该运行,那么这难道不会打乱脚本的执行顺序吗? - undefined
是的,你说得对 @trusktr,谢谢你的纠正。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接