-->

exec 'node app' hangs inside gulp task

2019-07-22 04:23发布

问题:

This gulp task hangs on exec('node config/app') line. first exec works fine but the second just hangs.

gulp.task('test', function(cb) {
    var exec = require('child_process').exec;

    exec('echo 3', function(err, stdout) {
        console.log(stdout);
    });

    exec('node config/app', function(err, stdout, stderr) {

        console.log(stdout);

        var testemOptions = {
            file: 'testem.json'
        };

        var t = new testem();

        return t.startCI(testemOptions, function() {
            cb();
        });
    });

});

I can see the output 3 but no output is shown for the second console.log.

I am trying to run my server before running the tests with testem.

I've tried this similar solution but it doesn't work: Exec not returning anything when trying to run git shortlog with nodejs.

Also I've recently asked a hanging testem gulp task question: Testem gulp task hangs after finished.

Edit:

My current solution is:

gulp.task('test', /*['build'],*/ function(cb) {
    var spawn = require('child_process').spawn;

    var proc = spawn('node', ['config/app']);

    proc.stdout.on('readable', function() {
        var output = proc.stdout.read();

        if (output && output.toString().match('express listening')) {

            var testemOptions = {
                file: 'testem.json'
            };

            var t = new testem();

            t.startCI(testemOptions, function() {
                proc.kill();
                cb();
            });
        }

    });

});

回答1:

If you want to use testem to test the "node config/app" server, you cannot use exec.

Exec is supposed to callback when the command is finished so in your case it will never callback.

try with

gulp.task('test', function(cb) {
    var spawn = require('child_process').spawn;

    var proc = spawn('node', ['config/app']);

    var testStarted = false;

    proc.stdout.on('readable', function() {

        if (testStarted) return;

        testStarted = true;

        var testemOptions = {
           file: 'testem.json'
        };

        var t = new testem();

        t.startCI(testemOptions, function() {
            proc.kill()
            cb();
        });

    }
});

Note that I did not test this code and that it probably does not handle all the corner cases you might encounter (if the server stops unexpectedly for example)

you may also want to check the plugin https://github.com/sargentsurg/gulp-testem



回答2:

There is ŧestem plugin on github.